blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
965f6ee7983db7fa1b5d10b9f220ad5d56894edc
JoseCordobaEAN/ProgramacionG320182
/Semana_11/ejercicios_while.py
2,143
4.21875
4
def de_la_z_a_la_a(): """ () -> list of str >>> de_la_z_a_la_a() ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] :return: list con las letras de la z a la a """ resultado = [] contador = 122 while contador > 96: resultado.append(chr(contador)) contador -= 1 return resultado def suma_pares(inferior, superior): """ (int, int) -> int Calcula la suma de todos los numeros pares en el rango inclusive >>> suma_pares(0, 10) 30 >>> suma_pares(2, 5) 6 >>> suma_pares(0, -1) 0 :param inferior: El limite inferior del rango :param superior: El limite superior del rango :return: La suma de todos los números pares en el rango """ pass def digitos(numero): """ (int) -> int Cuenta el numero de digitos dado un entero >>> digitos(10) 2 >>> digitos(1967) 4 >>> digitos(-20) 2 >>> digitos(0) 1 :param numero: :return: """ contador = 1 copia = abs(numero) while copia >= 10: contador += 1 copia //= 10 return contador def suma_digitos(numero): """ (int) -> int Cuenta el numero de digitos dado un entero >>> suma_digitos(10) 1 >>> suma_digitos(1967) 23 >>> suma_digitos(-20) 2 >>> suma_digitos(0) 0 :param numero: :return: """ acumulador = 0 copia = abs(numero) while copia > 0: acumulador += copia % 10 copia //= 10 return acumulador def lista_digitos(numero): """ (int) -> int Cuenta el numero de digitos dado un entero >>> lista_digitos(10) [1, 0] >>> lista_digitos(1967) [1, 9, 6, 7] >>> lista_digitos(-20) [-2, 0] >>> lista_digitos(0) [0] :param numero: :return: """ if numero == 0: return [0] acumulador = [] copia = abs(numero) while copia > 0: acumulador.insert(0, copia % 10) copia //= 10 if numero < 0: acumulador[0] *= -1 return acumulador
false
94330ced7a14e30c9471635029b5aab87a0053dc
juliopovedacs/datascience
/1. Python/Intro to Python course/bmi_program.py
221
4.1875
4
#Body Mass Index Python Program print("BMI PYTHON PROGRAM") height = input("What is your height? \n") weight = input("What is your weight? \n") bmi = height / weight ** 2 print("Your Body Mass Index is " + str(bmi))
false
9f7ab2ec4f7747b7c72e3815310403bcaf53bac8
ShushantLakhyani/200-Python-Exercises
/exercise_7.py
570
4.28125
4
# Q7) Write a Python program to construct the following pattern, using a nested for loop. # * # * * # * * * # * * * * # * * * * * # * * * * # * * * # * * # * #step 1: let a variable have the value 5, because of the final number of asterisks is 5 x = 5 # step 2: first 'for loop' to output the asterisks for the first 5 rows for n in range(x): for j in range(n): print('* ',end="") print('') # step 2: 'for loop' the number of asterisks for the last 4 rows for n in range(x,0,-1): for j in range(n): print('* ',end="") print(' ')
true
f4753e41101f6702cad27b5c62848e3afc1662a3
ShushantLakhyani/200-Python-Exercises
/exercise_5.py
538
4.4375
4
#Write a python program to check if a triangle is valid or not def triangle_validity_check(a,b,c): if (a>b+c) or (b>a+c) or (c>a+b): print("This is not a valid triangle.") elif (a==b+c) or (b==c+a) or (c==a+b): print("This can form a degenerated triangle.") else: print("These values can surely form a triangle.") side_1 = input("Input length of side 1:\n") side_2 = input("Input length of side 2:\n") side_3 = input("Input length of side 3:\n") triangle_validity_check(side_1,side_2,side_3)
true
2de6e4f4e6b61f97dc19627994d5d7fe04c0bcfd
ShushantLakhyani/200-Python-Exercises
/square_root__positive_number.py
247
4.21875
4
# Q3) Find the square root of a positive number #Declare a number in a variable a = 8 #to find thhe square root we raise the number to the power of 0.5, so raise a to the power of 0.5 a = a ** 0.5 # Now, print a to get the square root print(a)
true
c4ed80db929a1218c2bee51a9f6691b5a3677bcb
AtnuamInar/python_assignment_dec15
/q3.py
287
4.34375
4
#!/usr/bin/python3 num_list = [1, 2, 3, 4, 6, 7, 8, 9] def power(num_list): cube = list(); for num in num_list: cubed = num ** 3 cube += [cubed] return cube cube = power(num_list) print('Original list\t = {}\nCubed list\t = {}'.format(num_list, cube))
false
61133e6fa91e503cd0aa8370debc3140534d03a5
voygha/RedGraySearchservice
/ejer3_instrucciones_con_texto.py
968
4.28125
4
mi_cadena= "Hola mundo!" mi_cadena2= 'Hola mundo!' print(mi_cadena) #Si se va a mostrar comillas en una cadena, se debe poner una comilla contraria a las que se va a utilizar cadena_con_comillas= 'Javier dijo: "Hola Mundo"' print(cadena_con_comillas) comillas_simples= "Hello it's me!" print(comillas_simples) #EL \ INDICA QUE LAS "" QUE ESTAN DENTRO DE LA CADENA, PERTENECEN AL TEXTO cadena_con_comillas= "Javier dijo: \"Hola Mundo!\"" print(cadena_con_comillas) #A esto se le llama escapar y en python es usado para remover, en este caso eliminar el significado de las comillas #Para hacer esto se pone 3 " al principio y 3 " al final para armar el texto multilinea multilinea=""" Hola bienvenido. Actualmente estás en el curso de Python """ print(multilinea) nombre= "Luis" saludo= " Buenos días " union_cadena= nombre + saludo print(union_cadena) edad= 21 #Convierte en cadena cualquier valor numero_con_cadena= str(edad) print("Tu edad es: " + numero_con_cadena)
false
ba5ab5edaf9b9f85d5b95bc454e418d7cfc0cc6c
Paulvitalis200/Data-Structures
/Sorting/sort_list.py
1,641
4.125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head # split the list into two halves left = head right = self.getMid(head) tmp = right.next right.next = None right = tmp left = self.sortList(left) right = self.sortList(right) return self.merge(left, right) def getMid(self, head): slow, fast = head, head.next while fast and fast.next: slow= slow.next fast = fast.next.next return slow def merge(self, list1, list2): # tail will be the position we insert our merged node at # dummy allows us to avoid the edge case where we merge the two lists, the first node will be the head tail = dummy = ListNode() while list1 and list2: if list1.val < list2.val: tail.next = list1 list1 = list1.next else: tail.next = list2 list2 = list2.next # shift tail pointer so that we can add at the end of the list tail = tail.next if list1: tail.next = list1 if list2: tail.next = list2 # Return dummy.next to avoid putting the unnecessary node ListNode() return dummy.next # Input: head = [4,2,1,3] # Output: [1,2,3,4]
true
2db5ebe52b4e8512b8ae76e6f89165aa6a9cd095
alineat/python-exercicios
/desafio085.py
563
4.21875
4
# Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha # separados os valores pares e ímpares. No final, mostree os valores pares e ímapres em ordem crescente. num = [[], []] #valor = 0 for c in range(1, 8): valor = int(input(f"Digite o {c}º valor: ")) if valor % 2 == 0: num[0].append(valor) else: num[1].append(valor) print("-"*30) num[0].sort() num[1].sort() print(f"Todos os valores: {num}") print(f"Valores pares: {num[0]}") print(f"Valores ímapres: {num[1]}")
false
20cb8f53226940b8b42a70cc1d524d2a37e1d1e8
Ornella-KK/password-locker
/user_test.py
1,841
4.125
4
import unittest from user import User class TestUser(unittest.TestCase): def setUp(self): self.new_user = User("Ornella")#create user object def test_init(self): ''' test_init test case to test if the object is initialized properly ''' self.assertEqual(self.new_user.user_name,"Ornella") def test_save_user(self): ''' test_save_user test case to test if the user object is saved into the user list ''' self.new_user.save_user() self.assertEqual(len(User.user_list),1) def tearDown(self): ''' tearDown method that does clean up after each test case has run. ''' User.user_list = [] def test_save_multiple_user(self): ''' test_save_multiple_user to check if we can save multiple user objects to our user_list ''' self.new_user.save_user() test_user = User("user") test_user.save_user() self.assertEqual(len(User.user_list),2) def test_delete_user(self): ''' test_delete_user to test if we can remove a user from our user list ''' self.new_user.save_user() test_user = User("user") test_user.save_user() self.new_user.delete_user() #deleting a user object self.assertEqual(len(User.user_list),1) def test_user_exists(self): self.new_user.save_user() test_user = User("user") test_user.save_user() user_exists = User.user_exist("Ornella") self.assertTrue(user_exists) def test_display_all_user(self): ''' method that returns a list of all users saved ''' self.assertEqual(User.display_user(),User.user_list) if __name__ == '__main__': unittest.main()
true
564db3e5e03d18e980107ed59fa9dab7bfe0bfca
RizwanAliQau/Python_Practice
/try_excep_example.py
274
4.125
4
try: num = int(input(" enter a number")) sq_num = num * num print(sq_num) num1= int(input("enter second number of division")) b = num / num1 except ValueError: print('invalid number') except ZeroDivisionError: print("num2 can't be zero")
false
ba7389bd2476a80e1bd31936abce463963884f4d
DerrickChanCS/Leetcode
/426.py
1,837
4.34375
4
""" Let's take the following BST as an example, it may help you understand the problem better: We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. The figure below shows the circular doubly linked list for the BST above. The "head" symbol means the node it points to is the smallest element of the linked list. Specifically, we want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. We should return the pointer to the first element of the linked list. The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. """ """ # Definition for a Node. class Node(object): def __init__(self, val, left, right): self.val = val self.left = left self.right = right """ class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """ if root: head, _ = self.helper(root) return head return None def helper(self, root): head, tail = root, root if root.left: h, t = self.helper(root.left) t.right = root root.left = t head = h if root.right: h, t = self.helper(root.right) h.left = root root.right = h tail = t head.left = tail tail.right = head return (head,tail)
true
164ab46dfc6364b49b06b0bd442fe5e85bd6ca37
sushmeetha31/BESTENLIST-Internship
/Day 3 task.py
1,042
4.40625
4
#DAY 3 TASK #1)Write a Python script to merge two Python dictionaries a1 = {'a':100,'b':200} a2 = {'x':300,'y':400} a = a1.copy() a.update(a2) print(a) #2)Write a Python program to remove a key from a dictionary myDict = {'a':1,'b':2,'c':3,'d':4} print(myDict) if 'a' in myDict: del myDict['a'] print(myDict) #3)Write a Python program to map two lists into a dictionary keys = ['red','green','blue'] values = ['1000','2000','3000'] color_dictionary = dict(zip(keys, values)) print(color_dictionary) #4)Write a Python program to find the length of a set a = set([1,2,3,4,5)] print(len(a)) #5)Write a Python program to remove the intersection of a 2nd set from the 1st set s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} print("Original sets:") print(s1) print(s2) print("Remove the intersection of a 2nd set from the 1st set using difference_update():") s1.difference_update(s2) print(s1) s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} print("Remove the intersection of a 2nd set from the 1st set using -= operator:") print(s1-s2)
true
125eaf98db6359cb6d899c8e6aea55556c6c99f3
DKumar0001/Data_Structures_Algorithms
/Bit_Manipulation/Check_Power2.py
366
4.4375
4
# Check wheather a given number is a power of 2 or 0 def Check_pow_2(num): if num ==0: return 0 if(num & num-1) == 0: return 1 return 2 switch ={ 0 : "Number is 0", 1 : "Number is power of two", 2 : "Number is neither power of 2 nor 0" } number = int(input("Enter a Number")) case =Check_pow_2(number) print(switch[case])
true
ff61137fb930d6a2b211d8eeb1577ca67ec64924
YammerStudio/Automate
/CollatzSequence.py
490
4.28125
4
import sys ''' Rules: if number is even, divide it by two if number is odd, triiple it and add one ''' def collatz(num): if(num % 2 == 0): print(int(num/2)) return int(num/2) else: print(int(num * 3 + 1)) return int(num*3 + 1) print('Please enter a number and the Collatz sequence will be printed!') try: x = int(input()) except ValueError: print('Error: Invalid Value, only integer man') sys.exit() while x != 1: x = collatz(x)
true
5ec608e2a356eb31b0095da2153cedb1e74152d3
oreo0701/openbigdata
/Review/integer_float.py
801
4.1875
4
num = 3 num1 = 3.14 print(type(num)) print(type(num1)) print(3 / 2) # 1.5 print(3 // 2) # floor division = 1 print(3**2) #exponnet print(3%2) #modulus - distinguish even and odd print(2 % 2) #even print(3 % 2) #odd print(4 % 2) print(5 % 2) print(3 * (2 + 1)) #incrementing values num = 1 num = num + 1 num1 *= 10 #(num =num * 10) print(num) print(abs(-3)) #abs :absolute values print(round(3.75)) print(round(3.75, 1)) #round to the 1st digit of decimial num_1 = 3 # == comparision, = assignment num_2 = 2 print(num_1 != num_2) print(num_1 == num_2) print(num_1 < num_2) print(num_1 >= num_2) #number looks like string num_3 = '100' num_4 = '200' #concatenate together print(num_3 + num_4) # casting : cast string to integer num_3 = int(num_3) num_4 = int(num_4) print(num_3 + num_4)
true
f870ea6fa7baca5bb9c428128313c3a56ac80f4e
oreo0701/openbigdata
/Review/list_tuple_set.py
1,463
4.25
4
#list : sequential data courses = ['History', 'Math', 'Physic','CompSci'] print(len(courses)) #4 values in list print(courses[0]) print(courses[3]) print(courses[-1]) print(courses[-4]) print(courses[0:2]) print(courses[:2]) print(courses[2:]) #add values courses.append('Art') print(courses) #choose location to add courses.insert(0,'Eng') print(courses) courses_2 = ['Hello', 'Education'] courses.insert(0, courses_2) # add entire list print(courses) print(courses[0]) #combine two lists courses.extend(courses_2) print(courses) #remove courses.remove('Hello') print(courses) courses.pop() # remove last values of list print(courses) popped = courses.pop() print(popped) print(courses) courses.reverse() print(courses) nums = [1,5,2,4,3] nums.sort(reverse=True) print(courses) print(nums) print(min(nums)) print(max(nums)) print(sum(nums)) #sorted_courses = sorted(courses) #sorted version of list #print(sorted_courses) print(courses.index('CompSci')) print('Math' in courses) for item in courses: print(item) for index, course in enumerate(courses): #enumerate function print(index, course) for index, course in enumerate(courses, start =1): #enumerate function print(index, course) courses = ['History', 'Math', 'Physic','CompSci'] #join method course_str = ', '.join(courses) print(course_str) course_str = ' - '.join(courses) print(course_str) new_list = course_str.split(' -') print(course_str) print(new_list)
true
6b6cbd67e07c2dee71b95c03526a06d991102d48
SazonovPavel/A_byte_of_Python
/11_func_param.py
465
4.1875
4
def printMax(a, b): if a > b: print(a, 'максимально') elif a == b: print(a, 'равно', b) else: print(b, 'максимально') printMax(3, 4) # Прямая передача значений x = 5 y = 7 printMax(x, y) # передача переменных в качестве аргументов x = 5 y = 5 printMax(x, y) # передача переменных в качестве аргументов
false
af63ce394403b2e94f3d944c41b3669687dff4a2
GarryG6/PyProject
/String3_1.py
727
4.28125
4
# Задача 1. Определить, сколько раз в заданной строке встречается некоторый символ. st = input('Введите строку: ') sim = input('Введите символ: ') k = 0 # Переменная-счетчик for i in st: # Рассматриваем все номера символов строки в памяти компьютера if i == sim: # Сравниваем соответствующий символ с заданным k = k + 1 # Выводим ответ if k > 0: print('Заданный символ встречается в строке', k, 'раз') else: print('Такого символа нет')
false
63712a1d093a8d1def5e5e3edb697a6ef831d622
GarryG6/PyProject
/31.py
794
4.1875
4
# Дана последовательность чисел. Определить наибольшую длину монотонно возрастающего фрагмента # последовательности (то есть такого фрагмента, где все элементы больше предыдущего). n = int(input('Введите количество элементов ')) count = 1 max_ = 0 second = int(input('Введите элемент ')) for i in range(n - 1): first = int(input('Введите элемент ')) if first > second: count = count + 1 else: count = 0 if count > max_: max_ = count second = first print('Наибольшая длина последовательности = ', max_)
false
1bef673894fdda8f4671ec036532721bc30831d4
GarryG6/PyProject
/String13_1.py
1,072
4.25
4
# Задача 11. Дано предложение, в котором слова разделены одним пробелом (начальных и конечных пробелов нет). # Получить и вывести на экран два его первых слова. st = input('Введите предложение: ') # Получаем первое слово # Определяем позицию первого пробела pos = st.find(' ') # начиная с начала предложения # Определяем первое слово word1 = st[0:pos] print('Первое слово предложения: ', word1) # Переходим на следующий символ после первого пробела begin = pos + 1 # Определяем позицию второго пробела pos = st.find(' ', begin) # начиная с позиции begin # Определяем второе слово, используя срез word2 = st[begin:pos] print('Второе слово предложения: ', word2)
false
852a1cbe7932d9065b29b6d11f81c3bdc8db6227
nadiabahrami/c_war_practice
/level_8/evenorodd.py
272
4.4375
4
"""Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.""" def even_or_odd(number): return "Even" if number % 2 == 0 else "Odd" def even_or_odd_bp(num): return 'Odd' if num % 2 else 'Even'
true
58793a445e200a27bac54c49e397696d1ef94c3e
suiup/pythonProject
/python_learning/循环/while_learning.py
360
4.1875
4
print("while 循环演练") """ 语法: while 条件(判断 计数器 是否达到 目标次数): 条件满足 xxx 条件满足 xxx ... ... 处理条件(计数器 + 1) """ i = 0 while i <= 5: print("Hello world") if i == 3: i = i + 1 continue i= i + 1
false
4464f45eaf50f90ef887757f56d9ecd02ed7330c
imvera/CityUCOM5507_2018A
/test.py
500
4.21875
4
#0917test #print("i will now count my chickens") #print ("hens", 25+30/6) #print("roosters",100-25*3%4) #print("now count the eggs") #print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) #print("is it true that 3+2<5-7?") #print(3+2<5-7) #print("what is 3+2?",3+2) #print("what is 5-7?",5-7) #print("is it greater?",5 > -2) #print("is it greater or equal?",5 >= -2) #print("is it less or equal?",5 <= -2) #n = int(input('enter a number')) #while n >= 0: # print(n) # n=n-1 ## break #print('done!')
true
1a6195375e49cdcf2c06f3fd89f38134bc0ab80e
yukan97/python_essential_mini_tasks
/005_Collections/Task1_3_and_additional.py
508
4.25
4
def avg_multiple(*args): return sum(args)/len(args) print(avg_multiple(1, 2, 4, 6)) print(avg_multiple(2, 2)) def sort_str(): s = input("Eneter your text ") print(' '.join(sorted(s.split(' ')))) sort_str() def sort_nums(): num_seq_str = input("Please, enter your sequence ").split() try: num_seq = [int(x) for x in num_seq_str] print(sorted(num_seq, reverse=False)) except ValueError: print('You have entered not numbers into the sequence') sort_nums()
true
67dfa55500af7f9c1e0e57bcd96cb01b30d2353c
murchie85/hackerrank_myway
/findaString.py
1,407
4.1875
4
""" https://www.hackerrank.com/challenges/find-a-string/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen Sample Input ABCDCDC CDC Sample Output 2 Concept Some string processing examples, such as these, might be useful. There are a couple of new concepts: In Python, the length of a string is found by the function len(s), where is the string. To traverse through the length of a string, use a for loop: for i in range(0, len(s)): print (s[i]) A range function is used to loop over some length: range (0, 5) Here, the range loops over to . is excluded. # alternate options # USING STARTSWITH def count_substringBest(string, sub_string): count = 0 for i in range(len(string)): if string[i:].startswith(sub_string): count += 1 return count # USING SLICE def count_substringUsingSlice(string, sub_string): count = 0 for letter in range(0,len(string)): if(string[slice(letter,letter+len(sub_string,1)] == sub_string): count+=1 return(count) """ def count_substring(string, sub_string): count = 0 for letter in range(len(string)): if(string[letter:letter+len(sub_string)] == sub_string): count+=1 return(count) if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
true
a949ff5542b269ac60a8e8c6de555b9354c529c8
nadiavdleer/connectholland
/code/sortnum.py
1,020
4.125
4
""" Assessment problem 5 Nadia van der Leer for Connect Holland 10 June 2021 """ from word2number import w2n from num2words import num2words def sort_numerically(): # initialise word list word_list = [ "seventy five", "two hundred forty one", "three thousand", "one million thirty five thousand twelve", "twenty", "five hundred thousand", "two hundred", "one billion", ] i = 0 number_list = [] # convert each word to number, add to list for word in word_list: word = w2n.word_to_num(word_list[i]) i += 1 number_list.append(word) # sort number list in descending order number_list.sort(reverse = True) # convert numbers back to words, create new list num = 0 new_list = [] for number in number_list: number = num2words(number_list[num]) num += 1 new_list.append(number) return new_list if __name__ == "__main__": print(sort_numerically())
false
87e87abc6bcedda29a349fb945fd45541e8a681a
AirborneRON/Python-
/chatbot/chatBot.py
1,980
4.1875
4
file = open("stop_words") stopList = file.read().split("\n") file.close() # how to open up my plain text file, then create a variable to stuff the read file into #seperating each element of the list by the return key #then close # all responses should start with a space before typing print(" Hello ") response = raw_input(" what is your name ?") words = response.split(" ") for nextWord in words: if nextWord not in stopList: response = response.replace(nextWord, "") print("Well hello" +" " +nextWord) #because of how my stopList was formatted ive had to use the split function which has conflicted #with the String #print ("line 21" + nextWord) response = raw_input ("how lovely to meet you") if (response == "my names aaron"): print("how is that pronounced if you dont mind me asking ? ") response = raw_input( " Interesting name btw, my names Mac") if (response == " nice to meet you"): print("likewise") response = raw_input (" where are you from originally ? ") if (response == "im from cornwall originally"): print("oh I hear its beautiful down those parts") #if (response == "") response = raw_input("is there anywhere you'd want to go for a coffee there ?") if (response == " yes"): print("Great I look forward to it") elif(response == " no"): print("sod you then" + " i'll go by myself") response = raw_input("anyways, so how old are you ?") if (response == " 18"): print(" not as old as me then ") elif (response == " 23"): print("same age as me then") response = raw_input(" whats your favourite colour ?") if (response == "blue"): print("thats mine too") elif(response == "red"): print("red is sick" + " but unfortunetly we must end this conversation" ) elif(response == "yellow"): print ("yellows pretty cool too " + " anyways i really must be off TTFN") else: print("im not a fan of that colour" + "and on that note good day to you sir")
true
c451f37b2016ec1ad6b073a5bae922a98c72e270
RiverEngineer2018/CSEE5590PythonSPring2018
/Source Code/Lab3 Q3.py
2,249
4.34375
4
#Don Baker #Comp-Sci 5590 #Lab 3, Question 3 #Take an Input file. Use the simple approach below to summarize a text file: #- Read the file #- Using Lemmatization, apply lemmatization on the words #- Apply the bigram on the text #- Calculate the word frequency (bi-gram frequency) of the words (bi-grams) #- Choose top five bi-grams that has been repeated most #- Go through the original text that you had in the file #- Find all the sentences with those most repeated bi-grams #- Extract those sentences and concatenate #- Enjoy the summarization #Import Packages import nltk from nltk.tokenize import TweetTokenizer from nltk.stem import WordNetLemmatizer #Read Text File file_path = 'd:/Google Drive/UMKC/PhD/Classes/Python/Labs/Lab 3/Python_Lab3.txt' text_file = open(file_path,'r') text_data=text_file.read() text_file.close() #Using Lemmatization, apply lemmatization on the words #First step is to tokenize the data file into individual words tkn = TweetTokenizer() #create a tokenizer token = tkn.tokenize(text_data) #tokenize the data print("Tokenize: \n",(token),"\n") #print(token_results) #Now lemmatize the tokenize text file (noun is th default) wnl = WordNetLemmatizer() #create lemmatizer lem = [wnl.lemmatize(tkn) for tkn in token] print("Lemmatize (nouns): \n",lem,"\n") #Try lemmatizing looking for verbs wnl = WordNetLemmatizer() #create lemmatizer lem = [wnl.lemmatize(tkn,pos="v") for tkn in token] print("Lemmatize (verbs): \n",lem,"\n") #Try lemmatizing looking for adjectives wnl = WordNetLemmatizer() #create lemmatizer lem = [wnl.lemmatize(tkn,pos="a") for tkn in token] print("Lemmatize (adjectives): \n",lem,"\n") #Try lemmatizing looking for adverbs wnl = WordNetLemmatizer() #create lemmatizer lem = [wnl.lemmatize(tkn,pos="r") for tkn in token] print("Lemmatize (adverbs): \n",lem,"\n") #Apply bigram on the text #Grouping two words together. This includes special characters like '(' bigram = [tkn for tkn in nltk.bigrams(token)] print("Bigram: \n",bigram) #Calculate the Bigram Frequency freq_bi=nltk.FreqDist(bigram) #Find the 5 most common bigrams bi_common=freq_bi.most_common(5) print("\nThe 5 most common bigrams are:\n",bi_common)
true
49007104a978b21ad305c9ae13413da0dccd7e77
noy20-meet/meet2018y1lab4
/sorter.py
228
4.375
4
bin1="apples" bin2="oranges" bin3="olives" new_fruit = input('What fruit am I sorting?') if new_fruit== bin1: print('bin 1') elif new_fruit== bin2: print('bin 2') else: print('Error! I do not recognise this fruit!')
true
ed6f6da350b48cde11a0e7952aad238c590cca74
mkoryor/Python
/coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_brute.py
1,329
4.15625
4
""" Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed. Example 1: Input: "abdbca" Output: 3 Explanation: Palindrome pieces are "a", "bdb", "c", "a". Example 2: Input: = "cddpd" Output: 2 Explanation: Palindrome pieces are "c", "d", "dpd". """ # Time: O(2^n) Space: O(n) def find_MPP_cuts(st): return find_MPP_cuts_recursive(st, 0, len(st)-1) def find_MPP_cuts_recursive(st, startIndex, endIndex): # we don't need to cut the string if it is a palindrome if startIndex >= endIndex or is_palindrome(st, startIndex, endIndex): return 0 # at max, we need to cut the string into its 'length-1' pieces minimumCuts = endIndex - startIndex for i in range(startIndex, endIndex+1): if is_palindrome(st, startIndex, i): # we can cut here as we have a palindrome from 'startIndex' to 'i' minimumCuts = min( minimumCuts, 1 + find_MPP_cuts_recursive(st, i + 1, endIndex)) return minimumCuts def is_palindrome(st, x, y): while (x < y): if st[x] != st[y]: return False x += 1 y -= 1 return True def main(): print(find_MPP_cuts("abdbca")) print(find_MPP_cuts("cdpdd")) print(find_MPP_cuts("pqr")) print(find_MPP_cuts("pp")) print(find_MPP_cuts("madam")) main()
true
d7830b9e24ae1feeff3e2e7fce5b3db531adab73
mkoryor/Python
/coding patterns/dynamic programming/palindromic_subsequence/longest_palin_substring_topDownMemo.py
1,591
4.15625
4
""" Given a string, find the length of its Longest Palindromic Substring (LPS). In a palindromic string, elements read the same backward and forward. Example 1: Input: "abdbca" Output: 3 Explanation: LPS is "bdb". Example 2: Input: = "cddpd" Output: 3 Explanation: LPS is "dpd". Example 3: Input: = "pqr" Output: 1 Explanation: LPS could be "p", "q" or "r". """ # Time: O(N^2) Space: O(N^2) def find_LPS_length(st): n = len(st) dp = [[-1 for _ in range(n)] for _ in range(n)] return find_LPS_length_recursive(dp, st, 0, n - 1) def find_LPS_length_recursive(dp, st, startIndex, endIndex): if startIndex > endIndex: return 0 # every string with one character is a palindrome if startIndex == endIndex: return 1 if dp[startIndex][endIndex] == -1: # case 1: elements at the beginning and the end are the same if st[startIndex] == st[endIndex]: remainingLength = endIndex - startIndex - 1 # if the remaining string is a palindrome too if remainingLength == find_LPS_length_recursive(dp, st, startIndex + 1, endIndex - 1): dp[startIndex][endIndex] = remainingLength + 2 return dp[startIndex][endIndex] # case 2: skip one character either from the beginning or the end c1 = find_LPS_length_recursive(dp, st, startIndex + 1, endIndex) c2 = find_LPS_length_recursive(dp, st, startIndex, endIndex - 1) dp[startIndex][endIndex] = max(c1, c2) return dp[startIndex][endIndex] def main(): print(find_LPS_length("abdbca")) print(find_LPS_length("cddpd")) print(find_LPS_length("pqr")) main()
true
027f1de2e737fdc5556c86a83f0e7248c2812934
mkoryor/Python
/coding patterns/subsets/string_permutation.py
1,143
4.1875
4
""" [M] Given a string, find all of its permutations preserving the character sequence but changing case. Example 1: Input: "ad52" Output: "ad52", "Ad52", "aD52", "AD52" Example 2: Input: "ab7c" Output: "ab7c", "Ab7c", "aB7c", "AB7c", "ab7C", "Ab7C", "aB7C", "AB7C" """ # Time: O(N * 2^n) Space: O(N * 2^n) def find_letter_case_string_permutations(str): permutations = [] permutations.append(str) # process every character of the string one by one for i in range(len(str)): if str[i].isalpha(): # only process characters, skip digits # we will take all existing permutations and change the letter case appropriately n = len(permutations) for j in range(n): chs = list(permutations[j]) # if the current character is in upper case, change it to lower case or vice versa chs[i] = chs[i].swapcase() permutations.append(''.join(chs)) return permutations def main(): print("String permutations are: " + str(find_letter_case_string_permutations("ad52"))) print("String permutations are: " + str(find_letter_case_string_permutations("ab7c"))) main()
true
2c713bda8945104526d6784acdced81ae0681ad4
mkoryor/Python
/coding patterns/modified binary search/bitonic_array_maximum.py
957
4.1875
4
""" [E] Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1]. Example 1: Input: [1, 3, 8, 12, 4, 2] Output: 12 Explanation: The maximum number in the input bitonic array is '12'. Example 2: Input: [3, 8, 3, 1] Output: 8 """ # Time: O(logn) Space: O(1) def find_max_in_bitonic_array(arr): start, end = 0, len(arr) - 1 while start < end: mid = start + (end - start) // 2 if arr[mid] > arr[mid + 1]: end = mid else: start = mid + 1 # at the end of the while loop, 'start == end' return arr[start] def main(): print(find_max_in_bitonic_array([1, 3, 8, 12, 4, 2])) print(find_max_in_bitonic_array([3, 8, 3, 1])) print(find_max_in_bitonic_array([1, 3, 8, 12])) print(find_max_in_bitonic_array([10, 9, 8])) main()
true
83407eac0a8aaa8a71aa1631bbd17f5818dc877c
mkoryor/Python
/coding patterns/dynamic programming/longest_common_substring/subsequence_pattern_match_bottomUpTabu.py
1,261
4.15625
4
""" Given a string and a pattern, write a method to count the number of times the pattern appears in the string as a subsequence. Example 1: Input: string: “baxmx”, pattern: “ax” Output: 2 Explanation: {baxmx, baxmx}. Example 2: Input: string: “tomorrow”, pattern: “tor” Output: 4 Explanation: Following are the four occurences: {tomorrow, tomorrow, tomorrow, tomorrow}. """ # Time: O(m * n) Space: O(m * n) def find_SPM_count(str, pat): strLen, patLen = len(str), len(pat) # every empty pattern has one match if patLen == 0: return 1 if strLen == 0 or patLen > strLen: return 0 # dp[strIndex][patIndex] will be storing the count of SPM up to str[0..strIndex-1][0..patIndex-1] dp = [[0 for _ in range(patLen+1)] for _ in range(strLen+1)] # for the empty pattern, we have one matching for i in range(strLen+1): dp[i][0] = 1 for strIndex in range(1, strLen+1): for patIndex in range(1, patLen+1): if str[strIndex - 1] == pat[patIndex - 1]: dp[strIndex][patIndex] = dp[strIndex - 1][patIndex - 1] dp[strIndex][patIndex] += dp[strIndex - 1][patIndex] return dp[strLen][patLen] def main(): print(find_SPM_count("baxmx", "ax")) print(find_SPM_count("tomorrow", "tor")) main()
true
b2ae19549528e82aaec418c4bb32868ac9272b73
mkoryor/Python
/binary trees/diameterBT.py
1,697
4.3125
4
# A binary tree Node class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = self.right = None # utility class to pass height object class Height: def __init(self): self.h = 0 # Optimised recursive function to find diameter # of binary tree def diameterOpt(root, height): # to store height of left and right subtree lh = Height() rh = Height() # base condition- when binary tree is empty if root is None: height.h = 0 return 0 """ ldiameter --> diameter of left subtree rdiamter --> diameter of right subtree height of left subtree and right subtree is obtained from lh and rh and returned value of function is stored in ldiameter and rdiameter """ ldiameter = diameterOpt(root.left, lh) rdiameter = diameterOpt(root.right, rh) # height of tree will be max of left subtree # height and right subtree height plus1 height.h = max(lh.h, rh.h) + 1 # return maximum of the following # 1)left diameter # 2)right diameter # 3)left height + right height + 1 return max(lh.h + rh.h + 1, max(ldiameter, rdiameter)) # function to calculate diameter of binary tree def diameter(root): height = Height() return diameterOpt(root, height) # Driver function to test the above function """ Constructed binary tree is 1 / \ 2 3 / \ 4 5 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print( diameter(root) )
true
b6c8c4750c8feca766f8d199428d11f6d5410ec6
mkoryor/Python
/binary trees/inorder_traversal_iterative.py
657
4.15625
4
# Iterative function to perform in-order traversal of the tree def inorderIterative(root): # create an empty stack stack = deque() # start from root node (set current node to root node) curr = root # if current node is None and stack is also empty, we're done while stack or curr: # if current node is not None, push it to the stack (defer it) # and move to its left child if curr: stack.append(curr) curr = curr.left else: # else if current node is None, we pop an element from the stack, # print it and finally set current node to its right child curr = stack.pop() print(curr.data, end=' ') curr = curr.right
true
68db251c87295d02c092b7e521524f134b55d0a8
mkoryor/Python
/coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_bottomUpTabu.py
1,836
4.15625
4
""" Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed. Example 1: Input: "abdbca" Output: 3 Explanation: Palindrome pieces are "a", "bdb", "c", "a". Example 2: Input: = "cddpd" Output: 2 Explanation: Palindrome pieces are "c", "d", "dpd". """ # Time: O(N^2) Space: O(N^2) def find_MPP_cuts(st): n = len(st) # isPalindrome[i][j] will be 'true' if the string from index 'i' to index 'j' is a palindrome isPalindrome = [[False for _ in range(n)] for _ in range(n)] # every string with one character is a palindrome for i in range(n): isPalindrome[i][i] = True # populate isPalindrome table for startIndex in range(n-1, -1, -1): for endIndex in range(startIndex+1, n): if st[startIndex] == st[endIndex]: # if it's a two character string or if the remaining string is a palindrome too if endIndex - startIndex == 1 or isPalindrome[startIndex + 1][endIndex - 1]: isPalindrome[startIndex][endIndex] = True # now lets populate the second table, every index in 'cuts' stores the minimum cuts needed # for the substring from that index till the end cuts = [0 for _ in range(n)] for startIndex in range(n-1, -1, -1): minCuts = n # maximum cuts for endIndex in range(n-1, startIndex-1, -1): if isPalindrome[startIndex][endIndex]: # we can cut here as we got a palindrome # also we don't need any cut if the whole substring is a palindrome minCuts = 0 if endIndex == n-1 else min(minCuts, 1 + cuts[endIndex + 1]) cuts[startIndex] = minCuts return cuts[0] def main(): print(find_MPP_cuts("abdbca")) print(find_MPP_cuts("cdpdd")) print(find_MPP_cuts("pqr")) print(find_MPP_cuts("pp")) print(find_MPP_cuts("madam")) main()
true
db3da546c26b6d3c430ca62e18a2fc2127d76e60
mkoryor/Python
/coding patterns/dynamic programming/knapsack_and_fib/count_subset_sum_bruteforce.py
1,325
4.15625
4
""" Given a set of positive numbers, find the total number of subsets whose sum is equal to a given number ‘S’. Example 1: # Input: {1, 1, 2, 3}, S=4 Output: 3 The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3} Note that we have two similar sets {1, 3}, because we have two '1' in our input. Example 2: # Input: {1, 2, 7, 1, 5}, S=9 Output: 3 The given set has '3' subsets whose sum is '9': {2, 7}, {1, 7, 1}, {1, 2, 1, 5} """ # Time: O(2^n) Space: O(N) def count_subsets(num, sum): return count_subsets_recursive(num, sum, 0) def count_subsets_recursive(num, sum, currentIndex): # base checks if sum == 0: return 1 n = len(num) if n == 0 or currentIndex >= n: return 0 # recursive call after selecting the number at the currentIndex # if the number at currentIndex exceeds the sum, we shouldn't process this sum1 = 0 if num[currentIndex] <= sum: sum1 = count_subsets_recursive( num, sum - num[currentIndex], currentIndex + 1) # recursive call after excluding the number at the currentIndex sum2 = count_subsets_recursive(num, sum, currentIndex + 1) return sum1 + sum2 def main(): print("Total number of subsets " + str(count_subsets([1, 1, 2, 3], 4))) print("Total number of subsets: " + str(count_subsets([1, 2, 7, 1, 5], 9))) main()
true
1f567c01031206e9cd45c02f0590a36a0affde12
mkoryor/Python
/coding patterns/dynamic programming/longest_common_substring/longest_common_substring_topDownMemo.py
1,204
4.125
4
""" Given two strings ‘s1’ and ‘s2’, find the length of the longest substring which is common in both the strings. Example 1: Input: s1 = "abdca" s2 = "cbda" Output: 2 Explanation: The longest common substring is "bd". Example 2: Input: s1 = "passport" s2 = "ppsspt" Output: 3 Explanation: The longest common substring is "ssp". """ # Time: O(m * n) Space: O(m * n) def find_LCS_length(s1, s2): n1, n2 = len(s1), len(s2) maxLength = min(n1, n2) dp = [[[-1 for _ in range(maxLength)] for _ in range(n2)] for _ in range(n1)] return find_LCS_length_recursive(dp, s1, s2, 0, 0, 0) def find_LCS_length_recursive(dp, s1, s2, i1, i2, count): if i1 == len(s1) or i2 == len(s2): return count if dp[i1][i2][count] == -1: c1 = count if s1[i1] == s2[i2]: c1 = find_LCS_length_recursive( dp, s1, s2, i1 + 1, i2 + 1, count + 1) c2 = find_LCS_length_recursive(dp, s1, s2, i1, i2 + 1, 0) c3 = find_LCS_length_recursive(dp, s1, s2, i1 + 1, i2, 0) dp[i1][i2][count] = max(c1, max(c2, c3)) return dp[i1][i2][count] def main(): print(find_LCS_length("abdca", "cbda")) print(find_LCS_length("passport", "ppsspt")) main()
true
6dbb44e147405710f942350d732c2ec4c0d12a4f
kukiracle/curso_python
/python1-22/seccion5-7/50DiccionariosPARTE2.py
900
4.15625
4
# UN DICCIONARIO TIENE (KEY, VALUE)como un diccionario #es como un jason :V #para entrar a los elementos con la key'IDE' diccionario={ 'IDE':'integrated develoment eviroment', 'OOP':'Object Oriented Programming', 'DBMS':'Database Management System' } #RECCORER LOS ELEMENTOS for termino,valor in diccionario.items(): print(termino,valor) # solo los KEYS terminos for termino in diccionario.keys(): print(termino) #solo valores value for valor in diccionario.values(): print(valor) #comprobar si existe elemento en DICCIONARIO print('IDE' in diccionario) #agregar elementos de diccionario['PK']='primary key' print(diccionario) #remover elementos con pop diccionario.pop('DBMS') print(diccionario) #limpiar los elementos del diccionario diccionario.clear() #eliminar diccionario por completo deswde la memoria del diccionario print(diccionario)
false
adf515163aad1d273839c8c6ed2ca2d8503dfb9b
adamomfg/lpthw
/ex15ec1.py
1,187
4.59375
5
#!/usr/bin/python # from the sys module, import the argv module from sys import argv # Assign the script and filename variables to argv. argv is a list of # command lne parameters passed to a python script, with argv[0] being the # script name. script, filename = argv # assign the txt variable to the instance of opening the variable filename. txt = open(filename) # print the raw contents (read eval print loop!) of the instance of open # from the variable filename. print "Here's your file %r:" % filename # execute the read function on the open instantiation on filename print txt.read() # prompt the user of the script for the string representation of the file # that we had just opened. print "Type the filename again:" # assign the variable file_again to the string form of the input from the prompt file_again = raw_input(" ") # try to open the file with the name that's the string of the input just # given to the script. as in, instantiate the open method on the parameter # file_again, which is a string representation of the file's name txt_again = open(file_again) # print the contents of the file that was instantiated with the open command print txt_again.read()
true
92be2d072d41e740329b967749d113fb96a40882
amZotti/Python-challenges
/Python/12.2.py
993
4.15625
4
class Location: def __init__(self,row,column,maxValue): self.row = row self.column = column self.maxValue = float(maxValue) print("The location of the largest element is %d at (%d, %d)"%(self.maxValue,self.row,self.column)) def getValues(): row,column = [int(i) for i in input("Enter the number of rows and columns in the list: ").split(',')] l1=[] for k in range(row): l1.append([]) for i in range(row): print("Enter row: ",i) l1[i] = input().split() if len(l1[i]) == column: pass else: print("Invalid entry, Enter",column,"values,not",len(l1[i]),". Aborting!") break return l1 def locateLargest(): l1 = getValues() maxValue = max(max(l1)) row = l1.index(max(l1)) column = l1[row].index(maxValue) return Location(row,column,maxValue) def main(): locateLargest() if __name__ == "__main__": main()
true
6c311c48591efb25f6ab17bb06a906660800ac58
dchen098/bmi_calc
/bmi_calculator.py
424
4.15625
4
print("\n\t\t\tBMI Calculator\n\t\t\tMade by Daniel Chen\n\n") bmi=(int(input("What is your weight in pounds? "))*703)/(int(input("What is your height in inches? "))**2) t="underweight"if bmi<18.5 else"normal"if bmi<25 else"overweight"if bmi<30 else"obese" print("Your BMI is "+str(bmi)+"\nYou are "+t) print("Try losing some weight"if t=="obese"or t=="overweight"else"You are good"if t=="normal"else"Try gaining some weight")
false
b3fbd14eb0439bbb1249fd30112f81f1c72f2d51
lglang/BIFX502-Python
/PA8.py
2,065
4.21875
4
# Write a program that prompts the user for a DNA sequence and translates the DNA into protein. def main(): seq = get_valid_sequence("Enter a DNA sequence: ") codons = get_codons(seq.upper()) new_codons = get_sets_three(codons) protein = get_protein_sequence(new_codons) print(protein) def get_valid_sequence(prompt): seq = input(prompt) seq = seq.upper() nucleotides = "CATGX" for nucleotide in nucleotides: if nucleotide in seq: return seq else: print("Please enter a valid DNA sequence") return get_valid_sequence(prompt) def get_codons(seq): codons = [seq[i: i + 3] for i in range(0, len(seq), 3)] return codons def get_sets_three(codons): for item in codons: short = len(item) < 3 if short: codons.remove(item) return codons def get_protein_sequence(codons): gencode = {'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L', 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'TAT': 'Y', 'TAC': 'Y', 'TGT': 'C', 'TGC': 'C', 'TGG': 'W', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'} stop_codons = {'TAA': '*', 'TAG': '*', 'TGA': '*'} protein = [] for item in codons: if item in gencode: protein = protein + list(gencode[item]) if item in stop_codons: protein = protein + list(stop_codons[item]) return protein main()
true
1efa65530ee7adfb87f28b485aa621d7bab157ca
nat-sharpe/Python-Exercises
/Day_1/loop2.py
264
4.125
4
start = input("Start from: ") end = input("End on: ") + 1 if end < start: print "Sorry, 2nd number must be greater than 1st." start end for i in range(start,end): if end < start: print "End must be greater than start" print i
true
fb971ad16bda2bb5b3b8bff76105a45510bcc24c
fyupanquia/idat001
/a.py
469
4.125
4
name = input("Enter your name: ") worked_hours = float(input("How many hours did you work?: ")) price_x_hour = float(input("Enter your price per hour (S./): ")) discount_perc = 0.15; gross_salary = worked_hours*price_x_hour discount = gross_salary*discount_perc salary=gross_salary-discount print("") print("*"*10) print(f"Worker : {name}") print(f"Gross Salary : S./{gross_salary}") print(f"Discount (15%): S./{discount}") print(f"Salary : S./{salary}") print("*"*10)
true
a267eff041e8e97141b82ad952deee9cf83c8b5e
Saswati08/Data-Structures-and-Algorithms
/Heap/finding_median_in_a_stream.py
1,612
4.125
4
def balanceHeaps(): ''' use globals min_heap and max_heap, as per declared in driver code use heapify modules , already imported by driver code Balance the two heaps size , such that difference is not more than one. ''' # code here global min_heap global max_heap if len(max_heap) - len(min_heap) >= 2: heapq.heappush(min_heap,(heapq.heappop(max_heap)) * -1) elif len(min_heap) - len(max_heap) >= 2: heapq.heappush(max_heap, heapq.heappop(min_heap) * -1) def getMedian(): ''' use globals min_heap and max_heap, as per declared in driver code use heapify modules , already imported by driver code :return: return the median of the data received till now. ''' # code here global min_heap global max_heap if len(min_heap) == len(max_heap): return (max_heap[0] * -1 + min_heap[0])//2 else: if len(min_heap) > len(max_heap): return min_heap[0] else: return max_heap[0] * -1 def insertHeaps(x): ''' use globals min_heap and max_heap, as per declared in driver code use heapify modules , already imported by driver code :param x: value to be inserted :return: None ''' # code here global min_heap global max_heap if len(max_heap) == 0 or x < max_heap[0] * -1: heapq.heappush(max_heap, x * -1) else: heapq.heappush(min_heap, x) # print(max_heap, min_heap) min_heap = [] max_heap = [] n = int(input()) for i in range(n): insertHeaps(int(input())) balanceHeaps() print(getMedian())
false
fd66e0908166c686971c2164cb81331045a54f49
AniyaPayton/GWC-SIP
/gsw.py
1,714
4.375
4
import random # A list of words that word_bank = ["daisy", "rose", "lily", "sunflower", "lilac"] word = random.choice(word_bank) correct = word # Use to test your code: #print(word){key: value for key, value in variable} # Converts the word to lowercase word = word.lower() # Make it a list of letters for someone to guess current_word = [] for w in range(len(word)): current_word.append("_") print(current_word) # TIP: the number of letters should match the word # Some useful variables guess = [] maxfails = 3 fails = 0 count = 0 letter_guess = '' word_guess = '' store_letter = '' #you should make a loop where it checks the amount of letters inputted while fails < maxfails: guess = input("Guess a letter: ") #while count < fails: if letter_guess in word: print('yes!') store_letter += letter_guess count += 1 if letter_guess not in word: print('no!') count += 1 print('Now its time to guess. You have guessed',len(store_letter),'letters correctly.') print('These letters are: ', store_letter) #you don't need this because o fyour previous while loop. The one above #will only run until the user runs out of guesses while fails > maxfails: word_guess = input('Guess the whole word: ') while word_guess: if word_guess.lower() == correct: print('Congrats!') break elif word_guess.lower() != correct: print('Unlucky! The answer was,', word) break #check if the guess is valid: Is it one letter? Have they already guessed it? # check if the guess is correct: Is it in the word? If so, reveal the letters! print(current_word) #fails = fails+1 #print("You have " + str(maxfails - fails) + " tries left!")
true
a50ec0bb69075d06886309d4c8f95aa7e6b38ee2
awesometime/learn-git
/Data Structure and Algorithm/Data Structure/ListNode/TreeNode.py
1,644
4.34375
4
### 二叉树的产生及递归遍历 class TreeNode: def __init__(self, value=None, left=None, right=None): self.value = value self.left = left # 左子树 self.right = right # 右子树 root = TreeNode('D', TreeNode('B', TreeNode('A'), TreeNode('C')), TreeNode('E', right=TreeNode('G', TreeNode('F')))) print(root.value) #D print(root.left.value) #B print(root.left.left.value) #A print(root.right) # 地址 ### class Node: def __init__(self,value=None,left=None,right=None): self.value=value self.left=left #左子树 self.right=right #右子树 def preTraverse(root): ''' 前序遍历 ''' if root == None: return print(root.value) preTraverse(root.left) preTraverse(root.right) def midTraverse(root): ''' 中序遍历 ''' if root == None: return midTraverse(root.left) print(root.value) midTraverse(root.right) def afterTraverse(root): ''' 后序遍历 ''' if root == None: return afterTraverse(root.left) afterTraverse(root.right) print(root.value) if __name__=='__main__': # [原始二叉树图](https://www.cnblogs.com/freeman818/p/7252041.html) root=Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F')))) print('前序遍历:') preTraverse(root) print('\n') print('中序遍历:') midTraverse(root) print('\n') print('后序遍历:') afterTraverse(root) print('\n') ### 前序遍历: D B A C E G F 中序遍历: A B C D E F G 后序遍历: A C B F G E D ###
false
f873c177b269ff834f3cb930f14b17d6295c4c1c
kronicle114/codewars
/python/emoji_translator.py
837
4.4375
4
# create a function that takes in a sentence with ASCII emoticons and converts them into emojis # input => output # :) => 😁 # :( => 🙁 # <3 => ❤ ascii_to_emoji = { ':)': '😁', ':(': '🙁', '<3': '❤️', ':mad:': '😡', ':fire:': '🔥', ':shrug:': '¯\_(ツ)_/¯' } def emoji_translator(input, mapper): output = '' # take the input and split it words_list = input.split(' ') # use a forloop and in to figure out if the word is in the dict to map for word in words_list: if word in mapper: # if it is then add it but as the value of the ascii dict output += ' ' + mapper[word] else: # if the word is not there then add it to the string output output += word print(output) return output emoji_translator('hello :)', ascii_to_emoji)
true
8cfc878be48ddbf6fc5a6a977075b1691b4c44c6
IcefoxCross/python-40-challenges
/CH2/ex6.py
778
4.28125
4
print("Welcome to the Grade Sorter App") grades = [] # Data Input grades.append(int(input("\nWhat is your first grade? (0-100): "))) grades.append(int(input("What is your second grade? (0-100): "))) grades.append(int(input("What is your third grade? (0-100): "))) grades.append(int(input("What is your fourth grade? (0-100): "))) print(f"\nYour grades are: {grades}") # Data Sorting grades.sort(reverse=True) print(f"\nYour grades from highest to lowest are: {grades}") # Dropping lowest grades print("\nThe lowest two grades will now be dropped.") print(f"Removed grade: {grades.pop()}") print(f"Removed grade: {grades.pop()}") # Final printing print(f"\nYour remaining grades are: {grades}") print(f"Nice work! Your highest grade is a {grades[0]}.")
true
b0be90fabd5a0ba727f3e8c36d79aead438e20b5
TheOneTAR/PDXDevCampKyle
/caish_money.py
2,961
4.375
4
"""An account file ofr our Simple bank.""" class Account: """An Account class that store account info""" def __init__(self, balance, person, account_type): self.balance = balance self.account_type = account_type self.owner = person def deposit(self, money): self.balance += money self.check_balance() def withdraw(self, money): if money > self.balance: print("Insufficient funds. Apply for a loan today!!") else: self.balance -= money self.check_balance() def check_balance(self): print("Your account balance is ${:,.2f}".format(self.balance)) class Person: """A class that tracks Persons in our bank.""" def __init__(self, first_name, last_name, email): self.first_name = first_name self.last_name = last_name self.email = email self.accounts = {} def open_account(self, init_balance, account_name, account_type = 'checking'): self.accounts[account_name] = Account(init_balance, self, account_type) print("Your account is open!") self.accounts[account_name].check_balance() def close_account(self, index): del self.accounts[index] print("Please come back when you have more money.") def list_accounts(self): for account_name, account in self.accounts.items(): print("{} is a {} account with a balance of ${:,.2f}.".format( account_name, account.account_type, account.balance )) class Bank: """Our top-level class; controls Persons and their Accounts.""" def __init__(self): self.customers = {} self.savings_interest = 1.07 def new_customer(self, first_name, last_name, email): self.customers[email] = Person(first_name, last_name, email) def remove_customer(self, email): del self.customers[email] def show_customer_info(self, email): customer = self.customers[email] print("\nCustomer: {}, {}\nEmail: {}\n".format( customer.last_name, customer.first_name, customer.email )) print("Accounts:\n" + ("-" * 40)) customer.list_accounts() def customer_deposit(self, email, money, account_name): self.customers[email].accounts[account_name].deposit(money) def customer_withdraw(self, email, money, account_name): self.customers[email].accounts[account_name].withdraw(money) def make_customer_account(self, email, money, account_name, account_type="checking"): self.customers[email].open_account(money, account_name, account_type) if __name__ == '__main__': bank = Bank() bank.new_customer("Kyle", "Joecken", "kjoecken@hotmail.com") bank.make_customer_account("kjoecken@hotmail.com", 1000, "Primary Checking") bank.make_customer_account("kjoecken@hotmail.com", 10000, "Primary Savings", "savings") bank.show_customer_info("kjoecken@hotmail.com")
true
6e7622b6cc1de5399b05d7c52fe480f832c495ba
jacobkutcka/Python-Class
/Week03/hash_pattern.py
636
4.25
4
################################################################################ # Date: 02/17/2021 # Author: Jacob Kutcka # This program takes a number from the user # and produces a slant of '#' characters ################################################################################ # Ask user for Input INPUT = int(input('Enter the number of lines: ')) # Begin loop between 0 and INPUT for i in range(INPUT): # Begin output output = '#' # Count spaces requried for c in range(i): # Add spaces to output output += ' ' # Add final '#' to output output += '#' # Print output print(output)
true
4c5a6f6d8e2d5a076872f06d0484d9d5f6f85943
jacobkutcka/Python-Class
/Week03/rainfall.py
1,668
4.25
4
################################################################################ # Date: 03/01/2021 # Author: Jacob Kutcka # This program takes a year count and monthly rainfall # and calculates the total and monthly average rainfall during that period ################################################################################ def main(): # Establish sum sum = 0 # Call for year count years = int(input('Enter the number of years: ')) if years > 0: # Loop for each year for i in range(years): print(' For year No. ' + str(i+1)) # Add sum of rainfall in subject year sum += year(i) print('There are ' + str(years*12) + ' months.') print('The total rainfall is ' + str(format(sum, ',.2f')) + ' inches.') print('The monthly average rainfall is ' + str(format(sum/(years * 12), ',.2f')) + ' inches.') else: print("Invalid input.") def year(year): # Establish month list and sum sum = 0 months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] # Loop for each month for i in range(len(months)): # Find rain for subject month rainfall = float(input(' Enter the rainfall for ' + months[i] + '.: ')) while(rainfall < 0): # If rainfall is negative, inform user and ask again print(' Invalid input, please try again.') rainfall = float(input(' Enter the rainfall for ' + months[i] + '.: ')) # Add together all months' rainfall sum += rainfall # return rainfall sum return sum if __name__ == '__main__': main()
true
fe40e8644f98b8c2ebf6fedd95938c4dc95175d1
lukeyzan/CodeHS-Python
/LoopandaHalf.py
474
4.21875
4
""" This program continually asks a user to guess a number until they have guessed the magic number. """ magic_number = 10 # Ask use to enter a number until they guess correctly # When they guess the right answer, break out of loop while True: guess = int(input("Guess my number: ")) if guess == magic_number: print "You got it!" break print "Try again!" # Print this sentence once number has been guessed print "Great job guessing my number!"
true
312a6d67c228c81a4365681d8b116c5502ce5df8
LiamHooks/hw2p
/main.py
1,338
4.34375
4
# Author: Liam Hooks lrh5428@psu.edu # Collaborator: Seulki Kim svk6271@psu.edu # Collaborator: Angela Bao ymb5072@psu.edu # Collaborator: # Section: 2 # Breakout: 2 def getGradePoint(letter): if letter == "A": return 4.0 elif letter == "A-": return 3.67 elif letter == "B+": return 3.33 elif letter == "B": return 3.0 elif letter == "B-": return 2.67 elif letter == "C+": return 2.33 elif letter == "C": return 2.0 elif letter == "D": return 1.0 else: return 0.0 def run(): letter1 = input("Enter your course 1 letter grade: ") gradePoint1 = getGradePoint(letter1) credit1 = float(input("Enter your course 1 credit: ")) print(f"Grade point for course 1 is: {gradePoint1}") letter2 = input("Enter your course 2 letter grade: ") gradePoint2 = getGradePoint(letter2) credit2 = float(input("Enter your course 2 credit: ")) print(f"Grade point for course 2 is: {gradePoint2}") letter3 = input("Enter your course 3 letter grade: ") gradePoint3 = getGradePoint(letter3) credit3 = float(input("Enter your course 3 credit: ")) print(f"Grade point for course 3 is: {gradePoint3}") gpa = ((gradePoint1 * credit1) + (gradePoint2 * credit2) + (gradePoint3 * credit3)) / (credit1 + credit2 + credit3) print(f"Your GPA is: {gpa}") if __name__ == "__main__": run()
false
2e4d716798afd6e737492f33e56165a5de790aaf
rsaravia/PythonBairesDevBootcamp
/Level3/ejercicio4.py
418
4.4375
4
# Write a Python function using list comprehension that receives a list of words and # returns a list that contains: # a. The number of characters in each word if the word has 3 or more characters # b. The string “x” if the word has fewer than 3 characters low = ['a','este','eso','aquello','tambien'] lor = [len(x) if len(x) >= 3 else 'x' for x in low] print("Original list: ", low) print("Output list: ", lor)
true
6e438a337feb8ef59ca8c8deae05ea6bfcbe1c13
rsaravia/PythonBairesDevBootcamp
/Level1/ejercicio10.py
543
4.28125
4
# Write a Python program that iterates through integers from 1 to 100 and prints them. # For integers that are multiples of three, print "Fizz" instead of the number. # For integers that are multiples of five, print "Buzz". # For integers which are multiples of both three and five print, "FizzBuzz". l = [x+1 for x in range(100)] for each in l: if ( each%3 == 0 ) and ( each%5 == 0 ): print ("FizzBuzz") elif (each%3 == 0): print ("Fizz") elif (each%5 == 0): print ("Buzz") else: print(each)
true
5df3fa2d2ab2671f2302a582e95716d6a57dc09e
mariebotic/reference_code
/While Loops, For Loops, If Else Statements, & Boolean Operators.py
2,947
4.53125
5
# WHILE LOOPS, FOR LOOPS, IF ELSE STATEMENTS, & BOOLEAN OPERATORS #______________________________________________________________________________________________________________________________________________________________________________# import random while True: user_input = input("Please enter a number between 1 and 10: ") # asks user to enter a number between 1 and 10 if user_input.isnumeric(): # determines if the user input is all numerical values user_inputint = int(user_input) # changes user input string into an int if user_inputint <= 10 and user_inputint >= 1: # determines if the user input is less than or equal to 10 num = random.randint(1,10) # chooses a random int between 1 and 10 print(f"Your input is equal to the secret number: {user_inputint == num}") # determines if user input is equal to secret number print(f"Your input is not equal to the secret number: {user_inputint != num}") # determines if user input is not equal to secret number print(f"Your input is greater than the secret number: {user_inputint > num}") # determines if user input is greater than secret numer print(f"Your input is less than the secret number: {user_inputint < num}") # determines if user input is less than secret number print(f"The secret number is even: {num%2 == 0}") # determines if secret number is even guess = input("Please enter your guess for the secret number between 1 and 10: ") # asks user to enter a guess for the secret number between 1 and 10 if guess.isnumeric(): # determines if the user input is all numerical values guess = int(guess) # changes user input string into an int if guess <= 10 and guess >= 1: # determines if user input is less than or equal to 10 print(f"Your guess was {guess == num}, the secret number was {num}") # tells user if guess was correct and the value of the secret number for i in range(num): # prints numers up to but not equal to num print(i) response = input("Play again? ") # asks user if they want to play again if response == "y" or response == "yes" or response == "Yes" or response == "yes" or response == "YES": # accepted user responses continue # continue through while loop else: break # breaks while loop else: print("Your number was not between 1 and 10") # tells user that number was not between 1 and 10 else: print("Invalid type") # tells user that input was invalid else: print("Your number was not between 1 and 10") # tells user that number was not between 1 and 10 else: print("Invalid type") # tells user that input was invalid for i in range (1,11): # prints numbers 1 - 10 print(i) for i in "abc": # prints letters a - c print(i) #______________________________________________________________________________________________________________________________________________________________________________#
true
5b0b217cb0b2b4ef16066e9f2eb722347a7445ba
emjwalter/cfg_python
/102_lists.py
1,058
4.625
5
# Lists! # Define a list with cool things inside! # Examples: Christmas list, things you would buy with the lottery # It must have 5 items # Complete the sentence: # Lists are organized using: ___variables____????? # Print the lists and check its type dreams = ['mansion', 'horses', 'Mercedes', 'flowers', 'perfume'] print(dreams) print(type(dreams)) # Print the list's first object print(dreams[0]) # Print the list's second object print(dreams[1]) # Print the list's last object ### remember to include -1 at the end to find the last value in the list print(dreams[len(dreams)-1]) # Re-define the first item on the list and dreams[0] = 'chateau' print(dreams) # Re-define another item on the list and print all the list dreams[2]= 'BMW' print(dreams) # Add an item to the list and print the list dreams.append('husband') print(dreams) # Remove an item from the list and print the list dreams.remove('horses') print(dreams) # Add two items to list and print the list dreams.append('kitten') dreams.append('garden') print(dreams)
true
4cd98053e49db7a5422d7ec0c410325f228dd5d2
emjwalter/cfg_python
/104_list_iterations.py
707
4.34375
4
# Define a list with 10 names! register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Barry', 'Belle', 'Bertie', 'Becky', 'Belinda'] # use a for loop to print out all the names in the following format: # 1 - Welcome Angelo # 2 - Welcome Monica # (....) register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Barry', 'Belle', 'Bertie', 'Becky', 'Belinda'] count = 0 ## note to self: put the count before the block of code ## edit_r_list = [] for name in register: # print(name) # print(count) print(str(count) + ' - Welcome ' + name) edit_r_list.append(str(count) + ' - ' + name) count = count + 1 # optional print(edit_r_list) # Sweet! Now do the same using a While loop
true
ee9422e8c3398f0fae73489f6079517f2d3396b5
scress78/Module7
/basic_list.py
718
4.125
4
""" Program: basic_list.py Author: Spencer Cress Date: 06/20/2020 This program contains two functions that build a list for Basic List Assignment """ def get_input(): """ :returns: returns a string """ x = input("Please input a number: ") return x def make_list(): """ :returns: a list of numbers :raises ValueError: returned given non-numeric input """ number_list = [] for n in range(1, 4): x = get_input() try: x = int(x) number_list.append(x) except ValueError: print("Invalid Entry, please input a number") return number_list if __name__ == '__main__': make_list()
true
0ae7ca84c21ffaa630af8f0080f2653615758866
VertikaD/Algorithms
/Easy/highest_frequency_char.py
974
4.4375
4
def highest_frequency_char(string): char_frequency = {} for char in string: if char in char_frequency: char_frequency[char] += 1 else: char_frequency[char] = 1 sorted_string = sorted(char_frequency.items(), key=lambda keyvalue: keyvalue[1], reverse=True) print('Frequencies of all characters:', '\n', sorted_string) character = [] # defining empty list for t in sorted_string: # iterating over the sorted string to get each tuple # the first index[0] of each tuple i.e the characters is added in the list :character character.append(t[0]) return character[0] highest_frequency = highest_frequency_char( 'Program to find most repeated character') print('Most repeated character in the text is : ', '\n', '|', highest_frequency, '|') # vertical bar is used in case space came out to be the character with highest frequency
true
e3581004a1dffa98a99e8c08cfe52c78395e5331
RoaRobinson97/python
/binarySearch/main.py
1,079
4.125
4
#RECURSIVE def binary_search_recursive(arr, low, high, x): if high >= low: mid = (high + low) if arr[mid] == x: return mid elif arr[mid] > x: return binary_search_recursive(arr, low, mid - 1, x) else: return binary_search_recursive(arr, mid + 1, high, x) else: return -1 arr = [ 2, 3, 4, 10, 40 ] x = 10 result = binary_search_recursive(arr, 0, len(arr)-1, x) if result !=-1: print('Element is present at index', str(result)) else: print("Element is not present in the array") #ITERATIVE def binary_search_iterative(arr, x): low = 0 high = len(arr) - 1 mid = 0 while low <= high: mid = (high + low) if arr[mid] < x: low = mid + 1 elif arr[mid] > x: high = mid - 1 else: return mid return -1 arr2 =[2,3,4,4,10] x = 10 result2 = binary_search_iterative(arr2,x) if result2 != -1: print("Element is present at index:", str(result2)) else: print("Element is not present in array")
false
30c2f43d22e30ade58e703b3ac64176db33a3cbf
juancarlosqr/datascience
/python/udemy_machine_learning/02_simple_linear_regression/01_simple_linear_regression.py
2,083
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 19 13:49:10 2018 @author: jc """ import pandas as pd import numpy as np import matplotlib.pyplot as plt # data preprocessing # import dataset dataset = pd.read_csv('salary_data.csv') x = dataset.iloc[:, :-1].values dependant_column_index = 1 y = dataset.iloc[:, dependant_column_index].values # splitting dataset into training and test from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=1/3, random_state=0) # for simple linear regression, the library takes care of the feature scaling # feature scaling ''' from sklearn.preprocessing import StandardScaler x_sc = StandardScaler() x_train = x_sc.fit_transform(x_train) x_test = x_sc.transform(x_test) ''' # fitting simple linear regression to the training sets (x_train, y_train) from sklearn.linear_model import LinearRegression regressor = LinearRegression() # here the model is created, the model already learned from the data # in terms of machine learning, that is "machine" equals to the # simple linear regression model and the "learning" process is when # this model learned using the data provided to the fit method regressor.fit(x_train, y_train) # predicting values with test set (x_test) y_pred = regressor.predict(x_test) # visualizing the results # plotting observation values plt.scatter(x_train, y_train, color='red') # plotting the regression line # we use x_train in the predict method because we want # to plotthe predictions for the training set plt.plot(x_train, regressor.predict(x_train), color='green') plt.title('Salary vs Experience (Training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() # plotting test values (prediction) plt.scatter(x_test, y_test, color='red') # we can keep the same values here because will result # in the same model, the same line plt.plot(x_train, regressor.predict(x_train), color='green') plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
true
22ebee6a673d7af7cc1a34744d4efeaa07e5c92b
lukasz-lesiuk/algo-workshop
/algo-workshop.py
729
4.40625
4
def get_even_numbers(x, stop, z): """ Returns a list containing first 'x' even elements lower than 'stop'. Those elements must be divisible by 'z'. """ raw_list = [] for i in range(1,(stop//2)): raw_list.append(2*i) # print(raw_list) list_sorted = [] for element in raw_list: if element%z != 0: list_sorted.append(element) # print(list_sorted) for i in range(x): print(list_sorted[i]) def get_sum_of_greatest_elements(my_list, x): """ Returns a single integer, which is a sum of 'x' biggest elements from 'my_list' i.e. Returns a sum of 3 biggest elements from [2, 18, 5, -11, 7, 6, 9] """ pass get_even_numbers(2, 15, 10)
true
71c4b61ee65ceb5042908accca49af509fc43210
cyr1z/python_education
/python_lessons/02_python_homework_exercises/ex_03_lists.py
1,208
4.34375
4
""" Exercise: https://www.learnpython.org/en/Lists In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method. You must add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings variable. You will also have to fill in the variable second_name with the second name in the names list, using the brackets operator []. Note that the index is zero-based, so if you want to access the second item in the list, its index will be 1. """ numbers = [] strings = [] names = ["John", "Eric", "Jessica"] # write your code here # the variable second_name with the second name in the names list SECOND_NAME = names[1] # add the numbers 1,2, and 3 to the "numbers" list # using the "append" list method for i in range(1, 4): numbers.append(i) # add the words 'hello' and 'world' to the strings variable strings.append("hello") strings.append("world") if __name__ == "__main__": # this code should write out the filled arrays and the second # name in the names list (Eric). print(numbers) print(strings) print("The second name on the names list is %s" % SECOND_NAME)
true
8b9d35551a9f5b123a30c3e63ddf7f637eec279a
collins73/python-practice-code
/app.py
823
4.21875
4
# A simple program that uses loops, list objects, function , and conditional statements # Pass in key word arguments into the function definition my_name def my_name(first_name='Albert', last_name='Einstein', age=46): return 'Hello World, my name is: {} {}, and I am {} years old'.format(first_name,last_name, age) print(my_name('Henry', 'Ford', 96)) my_list = [1,2,3,4,5, "python", 43.98, "fish", True] my_list2 = ['grapes', 'oranges','Aegis', 100] new_list = my_list + my_list2 for letter in new_list: print(new_list) #check if the correct interger and string text is in the list if 20 in new_list and "python" in new_list: print("That is correct, this is the best programming langauge in the world!") else: print("Please chose the correct string or interger value!")
true
9ef773c250dab6e409f956fb10844b1e3a22015f
Zakaria9494/python
/learn/tuple.py
804
4.25
4
#A tuple is a collection which is ordered and unchangeable. # In Python tuples are written with round brackets. thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[1]) # negative Indexing #Print the last item of the tuple: print(thistuple[-1]) #range of index #Return the third, fourth, and fifth item: print(thistuple[2:5]) #Range of Negative Indexes #This example returns the items from index -4 # (included) to index -1 (excluded) print(thistuple[-4:-1]) ''' Tuple Methods Python has two built-in methods that you can use on tuples. Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found '''
true
978ed5bafbf3c3d796963d6152818fa68c230c52
Zakaria9494/python
/learn/inputuser.py
1,838
4.28125
4
# pyhon 3.6 input() # python 2.7 raw_input() # to get the functions of python in console # first step python eingeben #second step dir() #third step dir("") name =input("Was ist deine Name ? :") if len(name)< 2: print ("zu kurz") elif name.isalpha(): age = input("bitte geben Sie Alter ein: ") if age.isalpha(): print("bitte zahl eingeben!!") elif age.isdigit(): if int(age)< 18: klasse = input("Bitte geben Sie die KLasse ein:") if "abitur" in klasse: note = input("bitt geben Sie die note:") if float(note)<=1: print("Studienangebote:\n") print("Medizin","Jura") if int(note)>4: print("Schade") else: print("Sie können alles machen") elif name.isdigit(): print("bitte keine Zahlen eingeben") else: # convert the first charater to uppercas cpitalize # # or with casefold to lowercase x = name.capitalize() # center value string.center(length, charater) y= name.center(30) # 30 is the space " " print(x) print (y) """ # ASCII code print(ord("A"))# with this we read A in ascii and the output 65 print(chr(76)) print(chr(65)) print (ord("C")) print(ord("S")) print(chr(5)) #Indentation def function(): pass for each in "zakaria": pass # Single assignment city="London" money =100.3 count = 323 print(city, money, count) #multiple assignment a= b=c= 1 print(c, b , a) ''' Data types in python ''' # numbers, string, tuples, list , Dictionary x = 4 y = 5 if x > y: print(x) elif y < x or y> x : print (y) # identity operators x= 34 y=3434 print (id(y)) str1="zakaria" print(id(str1)) print(str1[0]) # print first letter print(len(str1)) # print the length """
false
e29a66a3557e2eabca2ebe273f0454222479c015
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex074.py
552
4.125
4
""" Exercício Python 074: Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla. """ from random import randint n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) print(f'\033[31mEu sortiei os valores \033[34m{n}\n') print(f'Os valores sorteados são: ', end='') for x in n: print(f'{x}', end=' ') print(f'\nO maior valor é {max(n)}') print(f'O menor valor é {min(n)}')
false
39461100d0a24ca1afecb91bbe628f319c6c56c0
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex081.py
869
4.1875
4
""" Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista. """ lista = list() cont = 0 while True: lista.append(int(input('Digite um valor: '))) cont += 1 escolha = ' ' while escolha not in 'SsNn': escolha = str(input('Continuar[S/N]: ')).strip()[0] if escolha in 'Nn': break print('-=-' * 20) print(f'Foram digitados {cont} valores') lista2 = lista[:] lista2.sort(reverse=True) print(f'A lista ordenada e de trás para frente fica: {lista2}') if 5 in lista: for c, v in enumerate(lista): if 5 == v: print(f'O valor 5 foi digitado e está na posição {c}') else: print(f'O 5 não foi digitado! ')
false
2572f07a5e1b2320bd3f19825b35eea43d963348
ericocsrodrigues/Python_Exercicios
/Mundo 02/ex062.py
764
4.21875
4
""" Exercício Python 62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos. """ barra = '\033[36m=\033[m' * 22 print(barra) print('\033[35m10 TERMOS DE UMA P.A\033[m') print(barra) n = int(input('Primeiro termo: ')) r = int(input('Razão: ')) termo = n c = 1 total = 0 mais = 10 while mais != 0: total += mais while c <= total: print(termo, end='') print(' → ' if c <= total else ' = ', end='') termo += r c += 1 print('PAUSA \033[31m◘\033[34m◘\033[30m◘') mais = int(input('Quantos termos a mais você quer ver? ')) print(f'FIM \033[31m☻\033[34m☻\033[30m☻\033[m, o total de termo foi {total}')
false
87c22b1d1b3f88e3737e20ac246dcf0cc300c793
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex078.py
643
4.125
4
''' Exercício Python 078: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. ''' lista = list() for x in range(5): lista.append(int(input(f'Digite um valor para a posição {x}: '))) print(f'O maior valor foi o {max(lista)} e está na posição: ', end='') for c, v in enumerate(lista): if v == max(lista): print(f'{c}...', end='') print() print(f'O menor valor foi o {min(lista)} e está na posição: ', end='') for c, v in enumerate(lista): if v == min(lista): print(f'{c}...', end='')
false
89d56e31f80950b8003903c7d20044b62d56a72a
eventuallyrises/Python
/CW_find_the_next_perfect_square.py
821
4.15625
4
#we need sqrt() so we import the build in math module import math #we start the function off taking in the square passed to it def find_next_square(sq): #for later we set up the number one higher than the passed square wsk=sq+1 # Return the next square if sq is a square, -1 otherwise #here we look to see if the passed number is a perfect square, if it is we look for the next one if math.sqrt(sq)%1==0: print("A Perfect Square! the next one is: ") #here we are looking for the next one by taking the current one incrementing by one and checking for perfection #im using a modulus on 1 of greater than 0 to check for perfection while math.sqrt(wsk)%1>0: wsk=wsk+1 return(wsk) else: return -1 #121->144 print(find_next_square(121))
true
d0e40a83f302dc6a0117634b7224494dd69ab992
KuroKousuii/Algorithms
/Prime numbers and prime factorization/Segmented Sieve/Simple sieve.py
832
4.15625
4
# This functions finds all primes smaller than 'limit' # using simple sieve of eratosthenes. def simpleSieve(limit): # Create a boolean array "mark[0..limit-1]" and # initialize all entries of it as true. A value # in mark[p] will finally be false if 'p' is Not # a prime, else true. mark = [True for i in range(limit)] # One by one traverse all numbers so that their # multiples can be marked as composite. for p in range(p * p, limit - 1, 1): # If p is not changed, then it is a prime if (mark[p] == True): # Update all multiples of p for i in range(p * p, limit - 1, p): mark[i] = False # Print all prime numbers and store them in prime for p in range(2, limit - 1, 1): if (mark[p] == True): print(p, end=" ")
true
862b61d7ff0c079159910d20570041da0d4747a3
jasimrashid/cs-module-project-hash-tables
/applications/word_count/word_count_one_pass.py
2,043
4.21875
4
def word_count(s): wc = {} # without splitting string beg = 0 c = '' word = '' word_count = {} for i,c in enumerate(s): # if character is end of line, then add the word to the dictionary if i == len(s)-1: #edge case what if there is a space at the end of line or special characters word += c.lower() if c not in [":",";",",", ".", "-", "+", "=", "/", "|", "[","]", "{", "}", "(", ")", "*", "^", "&",'"'] else c if word not in word_count: word_count[word] = 1 word = '' else: word_count[word] += 1 word = '' # if character is a whitespace, then add the word(concatenation of previous characters) to the dictionary elif c == ' ': if word not in word_count: word_count[word] = 1 word = '' else: word_count[word] += 1 word = '' #reset word # if character is: " : ; , . - + = / \ | [ ] { } ( ) * ^ &, skip it elif c in [":",";",",", ".", "-", "+", "=", "/", "|", "[","]", "{", "}", "(", ")", "*", "^", "&",'"']: # \ and quotes are special special cases continue #this skips character else: #when character is part of word word += c.lower() print(i, c, word) return word_count # edge cases # case 1: space in begninning / end "padding" # case 2: weird special characters # case 3: separate words with only punctuation in between but no spaces # case 4: two spaces if __name__ == "__main__": print(word_count('hello')) print(word_count('hello world hello')) print(word_count(' hello world')) print(word_count(' hello, world a ')) print(word_count("")) print(word_count("Hello")) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count('This is a test of the emergency broadcast network. This is only a test.')) print(word_count('Hello hello'))
true
f5812e58373f52e38f8efa72d8e4a6627526f194
prateek951/AI-Workshop-DTU-2K18
/Session1/demo.py
1,816
4.75
5
# @desc Working with Numpy import numpy as np # Creating the array using numpy myarray = np.array([12,2,2,2,2,2]) print(myarray) # The type of the array is np.ndarray whereas in python it would be list class print(type(myarray)) # To print the order of the matrix print(myarray.ndim) # To print the shape of the array print(myarray.shape) # To print a specific element of the array print(myarray[0]) # To print the last element of the array # 2 ways of printing the last element of the array print(myarray[len(myarray) - 1]); print(myarray[-1]) # Specific methods on the array that we can use # type(myarray) returns the type of the array # myarray.ndim returns the dimensions of the array # myarray.itemsize returns the size of the datatype that we have used for the array # myarray.size returns the size of the array # myarray.dtype returns the datatype of the array # For defining the 2 dimensional arraty using numpy myarray_2d = np.array([[13132,32,323,23,23],[32,32,32,323,2]]); print(myarray_2d) print(myarray_2d.shape) # Printing the dimensions of the array print(myarray_2d.ndim) print(len(myarray_2d)) # Negative index in numpy newarray = np.array([1,23132,12,122,1]) print(newarray[-1]) print(newarray[-2]) # Slicing in the array # Using the colon # myarray[:] : means all the elements print(newarray[:]) # Extracting the particular slice of the array print(newarray[1:3]) print(newarray[:-2]) #End of the splitting portion # To reverse the list of all the elements array_new = [13,123,132,121,2] print(array_new[::-1]) # Numpy functions to create arrays # To create the array of zeroes using numpy # np.zeroes() # To create an array of ones using numpy # np.ones() # To create the identity matrix using numpy # np.eye(4) to create a 4 dimensional identity matrix using numpy
true
58558f014aa28b29b9e2ad662cd783ff524bd220
prateek951/AI-Workshop-DTU-2K18
/Session-5 Working on Various Python Library/numpyops.py
2,447
4.375
4
my_list = [1,2,3] # Importing the numpy library import numpy as np arr = np.array(my_list) arr # Working with matrices my_matrix = [[1,2,3],[4,5,6],[7,8,9]] np.array(my_matrix) # Create an array np.arange(0,10) # Create an array keeping the step size as 2 np.arange(0,10,2) # Arrays of zeros np.zeros(3) # Array of zeros (3 rows and 3 columns) np.zeros((3,3)) # Array of ones np.ones(3) # Array of ones(3 rows and 3 columns) np.ones((3,2)) # Linspace returns an evenly spaced numbers over a specified interval np.linspace(0,5,10) # Create an identity matrix np.eye(4) # Create an array of random numbers from a uniform distribution from 0 to 1 np.random.rand(5) # Same thing but from a Normal Distibution centered around 0 np.random.randn(2) np.random.randn(2,2) np.random.randint(1,100,10) arr = np.arange(25) arr ranarr = np.random.randint(0,50,10) ranarr # Reshape method to get the same data but in new shape arr.reshape(5,5) # Finding the maximum element in the array ranarr.max() # Finding the index location of the maximum element in the array ranarr.argmax() # Finding the index location of the minimum element ranarr.argmin() # Print the shape of vector arr.shape # Reshape the vector to a 5,5 arr.reshape(5,5) arr.shape # Print the datatyoe of the array arr.dtype from numpy.random import randint randint(2,10) # Indexing and Selection in Numpy array newarr = np.arange(0,11) newarr newarr[8] # Performing slicing to get the slice of an array newarr[1:5] newarr[0:5] newarr[:6] newarr[5:] newarr[0:5] = 100 newarr newarr = np.arange(0,11) newarr # Creating the slice of an array slice_of_arr = arr[0:6] slice_of_arr[:] = 99 slice_of_arr # To create a copy of elements we can use the copy method arr_copy = arr.copy() arr arr_copy[:] = 100 arr # Indexing of a two dimensional array arr_2d = np.array([[5,10,15],[20,25,30],[35,40,45]]) arr_2d # Double bracket format # Element in the first row and the first column arr_2d[0][0] # Using the single bracket format arr_2d[1,1] arr_2d[1,2] arr_2d[2,1] arr_2d[:2,1:] # grab the first two rows arr_2d[:2] arr_2d[1:2] # Conditional Selection arr = np.arange(0,11) arr # This will give us a boolean vector bool_arr = arr > 5 arr[bool_arr] arr[arr>5] arr[arr<3] arr_2dim = np.arange(0,50).reshape(5,10) arr_2dim #Create the copy of the two dimensional array arr_2dim_copy = arr_2dim.copy() arr_2dim_copy arr_2dim[2,1:5] arr_2dim[1,3:5] arr_2dim[2,3:5]
true
e4db9a855ebaf188c4190ec4c564a0c46a3c573f
abhiis/python-learning
/basics/carGame.py
889
4.15625
4
command = "" is_started = False is_stopped = False help = ''' start: To start the car stop: To stop the car quit: To exit game ''' print("Welcome to Car Game") print("Type help to read instructions\n") while True: #command != "quit": if we write this condition, last else block always gets executed command = input("> ").lower() if command == "help": print(help) elif command == "start": if not is_started: print("Car Started") is_started = True else: print("Already Started!") elif command == "stop": if not is_stopped and is_started: print("Car Stopped") is_stopped = True else: print("Already Stopped!") elif command == "quit": print("Bye") break #this is loop control else: print("Sorry, I don't understand...Try Again")
true
c69077d4872fa21cddbf88b09cab2faf4c7010be
ryanZiegenfus/algorithms_practice
/codewars/challenges.py
2,239
4.125
4
##################################################################################################### # 1 # Create fibonacci sequence with n elements and ouptut it in a list. If n == 0 return empty list. # 0 1 1 2 3 5 8 11 19 ...etc # [0, 1, 1, 2, 3, 5,] def fib_sequence(n): base = [0, 1] if n == 0: return [] if n == 1: return [base[0]] if n == 2: return base if n > 2: counter = 2 while counter < n: print('looping') base.append(base[counter - 1] + base[counter - 2]) print(counter) counter += 1 return base # print(fib_sequence(7)) ##################################################################################################### # 2 # Create a tribonacci sequence with n elements and ouptut it in a list. If n == 0 return empty list. # 0 1 1 2 4 7 13 24 ...etc # [0, 1, 1, 2, 4, 7, 13, 24,] def trib_sequence(n): base = [0, 1, 1] if n == 0: return [] if n == 1: return [base[0]] if n == 2: return [base[0], base[1]] if n == 3: return base if n > 3: counter = 3 # only for first time!!! # base.append(base[0] + base[1] + base[2]) # base.append(0 + 1 + 1) while counter < n: base.append(base[counter - 3] + base[counter - 2] + base[counter - 1]) counter += 1 return base # print(trib_sequence(4)) ##################################################################################################### # 3 # Create a RECURSIVE tribonacci sequence with n elements and ouptut it in a list. If n == 0 return empty list. # 0 1 1 2 4 7 13 24 ...etc # [0, 1, 1, 2, 4, 7, 13, 24,] def outer_func(n): base = [0, 1, 1] if n == 0: return [] if n == 1: return [base[0]] if n == 2: return [base[0], base[1]] if n == 3: return base def rec_trib_sequence(): nonlocal n nonlocal base if len(base) == n: return base base.append(base[len(base)-1] + base[len(base)-2] + base[len(base)-3]) rec_trib_sequence() if n > 3: rec_trib_sequence() return base print(outer_func(7))
false
37ec44a4c625be4aff3bcb25f88822f9a13d5d87
l200183203/praktikum-algopro
/ainayah syifa prac 11 act 2.py
1,371
4.21875
4
#Practic 11. Activity 2. Make Simple Calculator. by@Ainayah Syifa Hendri from Tkinter import Tk, Label, Entry, Button, StringVar my_app = Tk(className= "Simple calculator") L1 = Label(my_app, text= "Number 1") L1.grid(row=0, column=0) str1 = StringVar() E1 = Entry(my_app, textvariable= str1) E1.grid(row=0, column=1, columnspan=3) L2 = Label(my_app, text= "Number 2") str2 = StringVar() L2.grid(row=1, column=0) E2 = Entry(my_app, textvariable= str2) E2.grid(row=1, column=1, columnspan=3) def plus(): p = float(str1.get()) q = float(str2.get()) r = p+q L.config(text=r) def minus(): p = float(str1.get()) q = float(str2.get()) r = p-q L.config(text=r) def times(): p = float(str1.get()) q = float(str2.get()) r = p*q L.config(text=r) def divide(): p = float(str1.get()) q = float(str2.get()) r = p/q L.config(text=r) B1 = Button (my_app, text= "+", command = plus) B1.grid(row=2, column=0) B2 = Button (my_app, text= "-", command = minus) B2.grid(row=2, column=1) B3 = Button (my_app, text= "x", command = times) B3.grid(row=2, column=2) B4 = Button (my_app, text= ":", command = divide) B4.grid(row=2, column=3) L3 = Label (my_app, text= "Results") L3.grid (row=3, column=1) L = Label(my_app, text= "0") L.grid(row=3, column=2) my_app.mainloop()
false
409e94361c99c3833dcc7990a2593b3ee5b10f10
amolgadge663/LetsUpgradePythonBasics
/Day7/D7Q1.py
393
4.1875
4
# #Question 1 : #Use the dictionary, #port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}, #and make a new dictionary in which keys become values and values become keys, # as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80} # port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"} print(port1) port1 = {value:key for key, value in port1.items()} print(port1)
true
517f5396a3e74f8f4c1f727a3224f21dc22be127
amolgadge663/LetsUpgradePythonBasics
/Day4/D4Q2.py
212
4.40625
4
# #Question 2 : #Explain using #islower() #isupper() #with different kinds of strings. # st1 = "I am Amol." print(st1) print("String isLower? ", st1.islower()) print("String isUpper? ", st1.isupper())
false
59125fe5d98160896e811a9be0cf6421a73e711c
DRCurado/Solids_properties
/Circle.py
744
4.21875
4
#Circle shape #Calculate the CG of a circle. import math #insert the inuts of your shape: unit = "mm" #insert the dimensions of your shape: diameter = 100; #Software do the calculations Area = math.pi*(diameter/2)**2; Cgx = diameter/2; Cgy = diameter/2; Ix= (math.pi*diameter**4)/64; Iy= (math.pi*diameter**4)/64; #Software print the results: print(""); print(" "); print("Welcome to the Circle Properties Calculator"); print("-----------------"); print("Area: "+str(Area)+unit+"^2"); print("-----------------"); print("CGx: "+str(Cgx)+unit); print("CGy: "+str(Cgy)+unit); print("-----------------"); print("Moment of inertia:"); print("X axix: "+str(Ix)+unit+"^4"); print("Y axix: "+str(Iy)+unit+"^4");
true
45e20efd919cb4ab2fc2b6b03449a8066b8f4f2a
alphaolomi/cryptography-algorithms
/transposition_encryption.py
1,122
4.1875
4
# Transposition Cipher Encryption def main(): my_message = 'Common sense is not so common.' my_key = 8 cipher_text = encrypt_message(my_key, my_message) # Print the encrypted string in cipher_text to the screen, with # a | (called "pipe" character) after it in case there are spaces at # the end of the encrypted message. print(cipher_text + '|') def encrypt_message(key, message): # Each string in cipher_text represents a column in the grid. cipher_text = [''] * key # Loop through each column in cipher_text. for col in range(key): pointer = col # Keep looping until pointer goes past the length of the message. while pointer < len(message): # Place the character at pointer in message at the end of the # current column in the cipher_text list. cipher_text[col] += message[pointer] # move pointer over pointer += key # Convert the cipher_text list into a single string value and return it. return ''.join(cipher_text) # the main() function. if __name__ == '__main__': main()
true
ca827f71d84324d576adac8192f0391af29a457c
rragundez/utility-functions
/ufuncs/random.py
699
4.1875
4
def generate_random_string(length, *, start_with=None, chars=string.ascii_lowercase + string.digits): """Generate random string of numbers and lowercase letters. Args: length (int): Number of characters to be generated randomly. start_with (str): Optional string to start the output with. chars: Types of characters to choose from. Returns: str: Randomly generated string with optional starting string. """ if start_with: start_with = '_'.join([start_with, '_']) else: start_with = '' rand_str = ''.join(random.choice(chars) for _ in range(length)) return ''.join([start_with, rand_str])
true
c10cb232f6c7b665dbf7fe0b672a8034dd97b6af
lukeitty/problemset0
/ps0.py
2,630
4.25
4
#Author: Luke Ittycheria #Date: 3/28/16 #Program: Problem Set 0 Functions #Function 0 def is_even(number): '''Returns a value if the number is even or odd''' if number == 0: return True if number % 2 == 0: return True else: return False return evenOrOdd ########################################################################### #Function 1 def num_digits(y): '''Calculates the amount of digits in a given number''' if y == 0: count = 1 return count count = 0 while y > 0: if y == 0: count += 1 count += 1 y = y/10 return count ########################################################################### #Function 2 def sum_digits(n): '''Calculates the sum of the digits in a given number''' if n == 0: return n s = 0 while n: s += n % 10 n //= 10 return s ########################################################################### #Function 3 def sum_less_ints(num): '''Calculates the sum of all the numbers below the given number''' if num == 0: sum = 0 return sum num = num - 1 sum = 0 while(num > 0): sum += num num -= 1 return sum ########################################################################### #Function 4 def factorial(z): '''Finds the factorial of a given number''' if z == 0: numero = 1 return numero numero = 1 while z >= 1: numero = numero * z z = z - 1 return numero ############################################################################ #Function 5 def factor(baseNum,factor2): '''Takes two positive integers and sees if the second number is a factor of the first''' if baseNum % factor2 == 0: return True else: return False ############################################################################ #Function 6 def primeNum(primeNum): '''Determines whether a number is prime or not (must be greater than 2)''' if primeNum == 2: return True for i in range(3, primeNum): if primeNum % i == 0: return False return True ############################################################################ #Function 7 def isperfect(n): '''Determines whether a number is perfect of not''' sum = 0 for x in xrange(1, n): if n % x == 0: sum += x return sum == n ############################################################################ #Function 8 def sumfactor(n): '''Takes the sum of the numbers digits and determines if it is a factor of the original number''' sum = sum_digits(n) factorNum = factor(n, sum) return factorNum ###########################################################################
true
39b91946afdb07d27c8314405268e89e842c8840
benichka/PythonWork
/favorite_languages.py
707
4.40625
4
favorite_languages = { 'Sara' : 'C', 'Jen' : 'Python', 'Ben' : 'C#', 'Jean-Claude' : 'Ruby', 'Jean-Louis' : 'C#', } for name, language in favorite_languages.items(): print(name + "'s favorite language is " + language + ".") # Only for the keys: print() for k in favorite_languages.keys(): print(k.title()) # It can be combined with other function: print() for k in sorted(favorite_languages.keys()): print(k.title()) # It also works with values: print() for v in favorite_languages.values(): print(v.title()) # To avoid duplicate, we transform the list into a set: print() for v in set(favorite_languages.values()): print(v.title())
true
618e1fdc6d658d3fc80cff91737e74f6f8fc30a6
benichka/PythonWork
/chapter_10/common_words.py
553
4.25
4
# Take a file and count occurences of a specific text in it. text_file = input("Choose a text file from which to count occurences of a text: ") occurence = input("What text do you want to count in the file?: ") try: with open(text_file, 'r', encoding="utf-8") as tf: contents = tf.read() except: print("Error trying to read the file.") else: occurence_count = contents.lower().count(occurence) print("There are " + str(occurence_count) + " occurences of the word " + occurence + " in the file " + text_file + ".")
true
d8947556c73c79505c31eb54718aecb20f1b1c2b
benichka/PythonWork
/chapter_10/addition.py
787
4.28125
4
# Simple program to add two numbers, with exception handling. print("Input 2 numbers and I'll add them.") while (True): print("\nInput 'q' to exit.") number_1 = input("\nNumber 1: ") if (number_1 == 'q'): break try: number_1 = int(number_1) except ValueError: print("\nOnly number are accepted.") continue number_2 = input("\nNumber 2: ") if (number_2 == 'q'): break try: number_2 = int(number_2) except ValueError: print("\nOnly number are accepted.") continue try: result = number_1 + number_2 except: print("\nError while adding " + number_1 + " and " + number_2 + ".") else: print(str(number_1) + " + " + str(number_2) + " = " + str(result))
true
c77c04ac341a2eb7e0f99ab4fb30b2f134c790d6
vit050587/Python-homework-GB
/lesson5.5.py
1,475
4.125
4
# 5. Создать (программно) текстовый файл, # записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. def sum_func(): try: with open('file_5.txt', 'w+') as file_num: str_num = input('Введите цифры через пробел \n') file_num.writelines(str_num) numbers = str_num.split() print(sum(map(int, numbers))) except IOError: print('Err!!!') except ValueError: print('Программа работает с числами! Вы вишли') sum_func() #--------------------------решение GB------------------------------ from random import randint with open("text.txt", "w", encoding="utf-8") as my_file: my_list = [randint(1, 100) for _ in range(100)] my_file.write(" ".join(map(str, my_list))) print(f"Sum of elements - {sum(my_list)}") # ------------------------------------------- вариант решения --------------------------------------------------------- from random import randint with open('task_5_file.txt', mode='w+', encoding='utf-8') as the_file: the_file.write(" ".join([str(randint(1, 1000)) for _ in range(100000)])) the_file.seek(0) print(sum(map(int, the_file.readline().split())))
false
8e0f68898778383bcc958dcade2b9f06910d1b61
ndpark/PythonScripts
/dogs.py
949
4.21875
4
#range(len(list)) can be used to iterate through lists dogs = [] while True: name = input('Dog name for dog # ' + str(len(dogs)+1) + '\nType in empty space to exit\n>>') dogs = dogs + [name] #Making a new list called name, and then adding it to dogs list if name == ' ': break print ('The dog names are:') for name in dogs: print('The name is ' + name) """for i in range(len(list)) print ('blah' + str(i) + 'blah' + list[i]) If you think about it it makes sense because 'in' and 'not in' can be written to check if something is in an array , similar to search something.index() can search which value that is passed example: spam = ['hello','google','dog','cat'] spam.index('hello') 0 etc spam.insert(1,'dog') will insert the index into the array sort() works --(reverse==True) to make it go reverse. Must all be the same type. remove() removes an element list is mutable; string is not. tuples are same as lists except immutble
true
8ade98a9e878e8ba1790be5e225372d9482b6cbb
ndpark/PythonScripts
/backupToZip.py
859
4.21875
4
#! python3 # backupToZip.py - Copies entire folder and its content into a zip file, increments filename import zipfile, os def backupToZip(folder): folder = os.path.abspath(folder) #Folder must be absolute #Figures out what the filename should be number = 1 while True: zipFilename = os.path.basename(folder) + '_'+ str(number) + '.zip' if not os.path.exists(zipFilename): break number = number +1 for foldername, subfolders, filenames in os.walk(folder): print('Adding files in%s...' % (foldername)) backupZip.write(foldername) for filename in filenames: newBase/ os.path.basename(folder)+'_' if filename.startswith(newBase) and filename.endswith('.zip') continue backupToZip.write(os.path.join(foldername,filename)) backupZip.close() print('Done') fileDir = input('Please insert filename') backupToZip(fileDir)
true
632a672805914b130a2de77eff69cc66af77c25c
rhitik26/python1
/python assignments/day4b.py
471
4.125
4
def outer(a): def inner(): print("this is inner!") print(type(a)) a() print("Inner finished execution!") return inner @outer #By adding this annotation the function will automatically become wrapper function(the concept is Decorator) def hello(): print("hello World!") @outer def sayhi(): print("hi world!") #demo1=outer(hello) # function hello is the wrapper function of sayhi, #demo2=outer(sayhi) hello() sayhi()
true
f0de78586e06ab3b4a740b1e0ca181d1e3fcb819
drkthakur/learn-python
/python-poc/python-self-poc/Calculator.py
437
4.15625
4
print(17/3) print(17//3) print(17%3) height=10 breadth=20 print(height*breadth) print (-3**2) print ((-3)**2) x=1 + 2*3 - 8/4 print(x) if 2.0 < 2: print("A") elif 2.0 >= 2: print("B") else: print("C") score = input("Enter Score: ") s = float(score) if s >= 0.9: print("A") elif s >= 0.8: print("B") elif s >= 0.7: print("C") elif s >= 0.6: print("D") elif s < 0.6: print("E") else: print("F")
false
13d7ab468faf1f3342bf8f221ca36e51437b131d
bloomsarah/Practicals
/prac_04/lottery_ticket_generator.py
778
4.1875
4
""" Generate program that asks for number of quick picks print that number of lines, with 6 numbers per line numbers must be sorted and between 1 and 45 """ import random NUMBERS_PER_LINE = 6 MIN = 1 MAX = 45 def main(): number_of_picks = int(input("Enter number of picks: ")) while number_of_picks < 0: print("Invalid number of picks.") number_of_picks = int(input("Enter number of picks: ")) for i in range(number_of_picks): pick = [] for j in range(NUMBERS_PER_LINE): number = random.randint(MIN, MAX) while number in pick: number = random.randint(MIN, MAX) pick.append(number) pick.sort() print(" ".join("{:2}".format(number) for number in pick)) main()
true
a4fe0d90b2772844969b34ce6ffa103c294ddfa1
timeeeee/project-euler
/4-largest-palindrome-product/main.py
358
4.15625
4
# Find the largest palindrome that is the product of 2 3-digit numbers. def isPalindrome(x): string = str(x) return "".join(reversed(string)) == string maximum = 0; for a in range(111, 1000): for b in range(111, 1000): product = a * b if isPalindrome(product) and product > maximum: maximum = product print maximum
true
206deca44b6fa1c1147d3c6d698d92ea2aee44ed
timeeeee/project-euler
/62-cubic-permutations/slow.py
1,720
4.15625
4
""" The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. """ from itertools import permutations class Cubes: def __init__(self): self.c = 1 self.cubes = set() self.max_cube = 0 def add_cube(self): new_cube = self.c ** 3 self.cubes.add(new_cube) self.max_cube = new_cube self.c += 1 def is_cube(self, n): while self.max_cube < n: self.add_cube() return n in self.cubes CUBE_COUNTER = Cubes() def test_cubes(): c = Cubes() tested_cubes = set() for x in range(1, 100): assert(c.is_cube(x**3)) tested_cubes.add(x**3) for x in range(10000): if x not in tested_cubes: assert(not(c.is_cube(x))) def cubic_permutations(n, number): count = 0 counted_so_far = set() for permutation in permutations(str(n)): p = int("".join(permutation)) if p > n and CUBE_COUNTER.is_cube(p) and p not in counted_so_far: print "permutation of {} {} is cube".format(n, p) counted_so_far.add(p) count += 1 if count == number: return True return False def find_cubic_permutations(start_base, number): while True: n = start_base ** 3 if cubic_permutations(n, number): return n start_base += 1 def main(): print find_cubic_permutations(340, 5) if __name__ == "__main__": main()
true