blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d2f53b00cae8731e03e804a43fbe06db53f340c6
cidexpertsystem/python-snippets
/isLucky.py
1,161
4.1875
4
# Ticket numbers usually consist of an even number of digits. # A ticket number is considered lucky if the sum of the first half # of the digits is equal to the sum of the second half. # Given a ticket number n, determine if it's lucky or not. import math def isLucky(n): # if sum of first half of digits equals sum of last half, return true # calculate sum of first half of digits if len(str(n)) % 2 == 0: # even number of digits index = int(len(str(n)) / 2) firstHalf = str(n)[:index] else: # odd number of digits length = math.floor(len(str(n))/2) firstHalf = str(n)[:length] sum = 0 for digits in firstHalf: sum += int(digits) # calculate sum of last half of digits if len(str(n)) % 2 == 0: # even number of digits length = math.floor(len(str(n))/2) lastHalf = str(n)[length:] else: # odd number of digits length = math.floor(len(str(n))/2) lastHalf = str(n)[length+1:] sum2 = 0 for digits in lastHalf: sum2 += int(digits) if sum == sum2: return True else: return False
true
1856263def6d2dee52316831dd29e8a92b4408fa
brunoczim/op-desafios
/desafio-03/JonathanLopes403/python/main.py
1,281
4.25
4
""" Esse progama mostrar todos os números palindrômicos entre um número e outro """ import sys def num_palindromicos(inicio, fim): """ Essa função é responsavel por gerar os números palindrômicos """ #Conjunto dos números que são palindrômicos palindromicos = set() # Verifica se fim é menor que inicio e se o número é maior que um unsigned int de 64 bits if inicio > 18446744073709551615 or fim > 18446744073709551615: print("Os números passados devem ser menor que 18446744073709551615!") sys.exit(1) elif fim < inicio: print ("Número de fim é menor que o do inicio!") sys.exit(1) # Verifica se os números passados são positivos: if inicio < 0 or fim < 0: print("Só devem ser passado números positivos!") sys.exit(1) # Printa os números palindrômicos for numero in range(inicio, fim+1): # Convertendo o número para string para verificar se é palindrômico reverse_number = str(numero)[::-1] if str(numero) == reverse_number: palindromicos.add(numero) return palindromicos numeros = num_palindromicos(0, 1000) # Colocando em Ordem Crescente numeros_ordenados = list(numeros) numeros_ordenados.sort() print(numeros_ordenados)
false
1811759e340d506fa6574deb9ae9d4bb43912d10
theblacksigma/Py9ft
/5. Python progra to calculate Area of Right Angled Triangle.py
346
4.34375
4
#Python progra to calculate area of Right Angled Triangle b=int(input("Enter base of the right angled triangle:")) p=int(input("Enter perpendicular height of the right angled triangle:")) h=(b**2+p**2)**(1/2) x=b+p+h a=(1/2)*b*p print("Perimeter of Right Angled Triangle:",x,"units") print("Area of Right Angled Triangle:",a,"sq units")
true
645b76d43eb988a42ce1daf1d5832eeb65a651b7
matthewzar/CodeWarsKatas
/Python/Kyu8/PositiveNegativeCount/PositiveNegativeCount.py
923
4.21875
4
''' https://www.codewars.com/kata/count-of-positives-slash-sum-of-negatives/train/python Count positive numbers, and sum negatives. ''' def count_positives_sum_negatives(arr): if(arr == []): return [] return [sum([1 if x > 0 else 0 for x in arr]), sum([x if x < 0 else 0 for x in arr])] import unittest class TestStringMethods(unittest.TestCase): def test_counts(self): self.assertEqual(count_positives_sum_negatives([1, -15]),[1,-15]) self.assertEqual(count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]),[10,-65]) self.assertEqual(count_positives_sum_negatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]),[8,-50]) self.assertEqual(count_positives_sum_negatives([1]),[1,0]) def test_empty(self): self.assertEqual(count_positives_sum_negatives([]),[]) if __name__ == '__main__': unittest.main()
false
192eccf887cad1887c94db578a1d7d02904f3530
kinjal2110/PythonTutorial
/39_comprehension.py
1,254
4.21875
4
# ls = [] # for i in range(50): # if i%3==0: # ls.append(i) #i module 3 ==0 value print # above things we can also done by list comprehensions # -----------------------------------------------list comprehension----------------------------------- ls = [i for i in range(50) if i %3==0] #it is list comprehension. print(ls) # dic = {0:"item0", 1:"item1"} #simple method #----------------------------------------dictionary comprehension---------------------------------------- dic = { i: f"Item {i}" for i in range(50) if i %2 ==0 } dic1 = {value:key for key, value in dic.items()} #using this dictionary will be decreasing order print(dic) print(dic1) # -----------------------------------set comprehension------------------------------------------------------- dresses = {dress for dress in ["dress1", "dress2", "dress1", "dress3"]} #repeated value will be not print every time print(dresses) print(type(dresses)) #it is class set. # -----------------------------------------generator comrehension-------------------------------------------- even = (i for i in range(50) if i % 2 ==0) print(type(even)) print(even.__next__()) print(even.__next__()) print(even.__next__()) print(even.__next__())
true
61ed971df85f240a7c33ea84425ada21cec640f2
kinjal2110/PythonTutorial
/38_generator.py
953
4.28125
4
''' Itersble- __iter__() or __getitem__ Iterator __next__() Iteration ''' def gen(n): for i in range(n): # return i yield i #it is return value g =gen(3) for i in g: print(i) for i in range(6): print(i) # using generator factorial print("Factorial is: ") def fact(n): sum = 1 for i in range(n, 0): sum = sum * i yield sum #it will generate value on the fly, saving ram f = fact(4) print(f) #it will return memory location. # ----------------------------------------iter, iterator, iteration------------------------------------ k = "kinjal" print(iter(k)) #iter object address will return. p = iter(k) print("next: ",p.__next__()) print("next: ",p.__next__()) print("next: ",p.__next__()) print("next: ",p.__next__()) print("next: ",p.__next__()) print("next: ",p.__next__()) for c in k: print(c) #string will print one by one character. it is iterator
false
fc8a0e66310d9b4b30dff5addcdf4f01e026b489
kinjal2110/PythonTutorial
/8.py
867
4.25
4
#Exercise:- Take user input, and we need to say user to those number or less then or greater then number # which already has an over program.(it likes binary search). # if n=18 # number of guesses is 9 # we need to print number of guesses left # number of guesses he took to finish. # if all guesses left then print "game over" n=18 n_of_guess=1 print("Number of guess is limited to 9") while(n_of_guess<=9): in1 = int(input("Guess any number:")) if in1<18: print("you enter less number please input greater number") elif in1>18: print("you enter greater number please input smaller number") else: print("you won") print("number of guesses you took to finish") break print(9-n_of_guess, "number of guesses left") n_of_guess= n_of_guess + 1 if(n_of_guess>9): print("game over")
true
d32ee087bf3d78c6a64b676ba841df8023e4edde
alexandru-dinu/competitive-programming
/leetcode/implement_trie_prefix_tree.py
923
4.1875
4
# https://leetcode.com/problems/implement-trie-prefix-tree class Trie: def __init__(self): self.kids = {} # char -> Trie self.is_end = False def walk(self, word: str) -> Optional["Trie"]: t = self for c in word: if c not in t.kids: return None t = t.kids[c] return t def insert(self, word: str) -> None: t = self for c in word: if c not in t.kids: t.kids[c] = Trie() t = t.kids[c] t.is_end = True def search(self, word: str) -> bool: t = self.walk(word) return t is not None and t.is_end def startsWith(self, prefix: str) -> bool: return self.walk(prefix) is not None # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
false
aa49e54950f552058444b70b8c3385321018ae7f
Astrolopithecus/PalindromeChecker
/palindromeChecker.py
1,088
4.21875
4
# Miles Philips # prog 260 # 7-10-19 # Palindrome Detection program from stack import Stack #Implement this function that checks whether the input string is a palindrome: # (a string where the characters of the string read the same when read backward # as forward. E.g. racecar, mom) def palindromeCheck(mystr): word = Stack() for char in mystr: word.push(char) while word.size() >=2: for char1 in mystr: char2 = word.pop() if char1 != char2: return False return True def main(): print("Welcome to the Palindrome check program.") ans = 'y' while ans == 'y': expression = input("Enter the string you want to check: ") isAPalindrome = palindromeCheck(expression) if isAPalindrome: print(f"'{expression}' is a palindrome") else: print(f"'{expression}' is NOT a palindrome") ans = input("Continue?(y/n): ").lower() print("Goodbye") if __name__ == "__main__": main()
true
d796fa0e2daf167745ac995e14b6f6ea65a30425
wernicka/learn_python
/example_prgms/ex6.py
1,071
4.5625
5
# set variable types_of_people to an integer: 10 types_of_people = 10 # set variable x to a string: sentence about types_of_people. x = f"There are {types_of_people} types of people" # unnecessarily set values of binary and do_not to strings binary = "binary" do_not = "don't" # set variable y to another string which has two instances of placing strings within strings y = f"Those who know {binary} and those who {do_not}." #print variable x and y print(x) print(y) #instance 3 of placing a string within a string print(f"I said: {x}") #instance 4 of placing a string within a string print(f"I also said: '{y}'") hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" #instance 5 of placing a string within a string, because .format converts the boolean value of hilarious to a string and places it within the string set to variable joke_evaluation. print(joke_evaluation.format(hilarious)) # set variables w and e to strings w = "This is the left side of..." e = "a string with a right side." # print variable w and variable e together print(w + e)
true
191362f0e7bd2ab6bbe104b1d65304e373dafc3f
wernicka/learn_python
/original_code/Algorithms/2_integer_array.py
1,233
4.375
4
# You are given an array (which will have a length of at least 3, but could be very large) containing integers. # The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single # integer N. Write a method that takes the array as an argument and returns N. # For example: # [2, 4, 0, 100, 4, 11, 2602, 36] # Should return: 11 # [160, 3, 1719, 19, 11, 13, -21] # Should return: 160 def odd_one_out(input_array): count_evens = 0 count_odds = 0 for item in input_array: if item % 2 == 0: last_even_value = item count_evens +=1 else: last_odd_value = item count_odds +=1 if count_odds > count_evens: return last_even_value else: return last_odd_value print(odd_one_out([2, 4, 0, 100, 4, 11, 2602, 36])) print(odd_one_out([160, 3, 1719, 19, 11, 13, -21])) # NOTES FROM BEFORE I STARTED CODING # determine whether each value in array is divisible by two - for loop? # store the last odd value and the last even value in variables # count up how many are even and how many are odd # if count of odd > count of even, return even variable # else return odd variable
true
e2b029a70231d60abb74d730e81372904909f7eb
mutemibiochemistry/Biopython
/exercise11functions/question4.py
394
4.21875
4
#Write a function that accepts a single integer parameter, and returns True if the number is prime, otherwise False. a=int(raw_input("Enter number: ")) def isprime(a): #return True if the number is prime, false otherwise if (a == 1) or (a == 2): return "is True" else : for i in range(2, a ): if a%i == 0: return str(a)+" is False" return str(a)+" is true" print isprime(a)
true
0c7faa1a84483918796097fa8b70c3d5fb60f208
mutemibiochemistry/Biopython
/exercise5/question9.py
242
4.28125
4
#enters sequence of nos ending with a blank line then prints the smallest nos = raw_input("Enter numbers: ") smallest = nos while nos != '': if int(nos) < int(smallest): smallest = nos nos = raw_input("Enter numbers: ") print smallest
true
d981b1f0bf529307d8053f8d324d87d5132a8977
MCNANA12/pycharmdupdated
/Hello World.py
732
4.4375
4
# Basic string Operation str = 'Hello World, this is a string!' print(len(str)) # Get the length print(str * 3) # Repeat print(str.replace('Hello', 'Hola')) # Replace print(str.split(',')) # Split print(str.startswith('H')) # starts with print(str.endswith('!')) print(str.lower()) print(str.upper()) # slicing - or getting a sub string print(str[0:4]) # Get the fisrt 5 - zero based print(str[6:]) # Get the 6th to the end print(str[-7:]) # Get the last 7 print(str[6:11]) # Get the 6 to 11 # indexs - the position of l = ',' c = str.find(l) # -1 if not found print(f'Find returned {c}') i = str.index(l) # Will throw an error! print(f'Find returned {i}') x = str[:i] print(x) #lists you create with square brackets
true
f9765623e0b33467cd76e4f439b29f077985b1a2
FstRms/basic-python
/BMI.py
610
4.34375
4
""" Script to calculate Body Mass Index""" print("Hi there!!!\nWelcome to the Body Mass Index Calculator tool!!!\n") height = float(input("Please enter your height in m:\n")) weight = float(input("Please enter your weight in kg:\n")) bmi = int(weight / (height ** 2)) if bmi < 18.5: print (f"Your BMI is {bmi}. You are Underweight") elif bmi < 25: print (f"Your BMI is {bmi}. You have Normal weight") elif bmi < 30: print (f"Your BMI is {bmi}. You have Overweight") elif bmi < 35: print (f"Your BMI is {bmi}. You have Obesity") else: print("Your BMI is {bmi}. You have Clinnical Obesity")
false
761dee0913c11def9e5eb5574602917184325c1d
Riceps/cp1404_practicals
/prac_02/exceptions_demo.py
754
4.25
4
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? 2. When will a ZeroDivisionError occur? 3. Could you change the code to avoid the possibility of a ZeroDivisionError? """ try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.") # 1. A value error will occur when the user inputs a value that is NOT an integer for the num or den. # 2. A Zero division error will occur if the user inputs a "0" for the denominator value. # 3. Yes
true
7a1d6919281d2a8ef58faa4ab2ad5ef27cf8b831
Riceps/cp1404_practicals
/prac_01/loops.py
526
4.21875
4
"Prints all numbers between 1 and 20 inclusive, with a step of 2 (i.e. all odd numbers)" for i in range(1, 21, 2): "prints number i and a space TODO:(question what (end) does)" print(i, end=' ') print() for i in range(0, 101, 10): print(i, end=' ') print() for i in range(20, 0, -1): print(i, end=' ') print() number_of_stars = int(input("Enter a whole number of stars: ")) for i in range(number_of_stars): print("*", end=' ') print() for i in range(1, number_of_stars + 1): print('*' * i) print()
true
0630dd5fb3b671748d9a3051b55c26238580351a
reedcwilson/programming-fundamentals
/lessons/2/homework/fibonacci.py
804
4.25
4
# import some modules so that we get some extra functionality # ask for the option they would prefer (nth number or number <= n) # if you recognize their choice then continue # ask for the n # keep track of the current first and second numbers # if we are option number 1 do the nth number algorithm # for option 1, loop for n times # modify the first and second variables based on new number # print the answer # if we are option number 2 do the <= n algorithm # for option 2, loop while we are <= n # modify the first and second variables based on new number # print the answer # otherwise let them know that you didn't understand their choice # wait for the user to press enter to quit # clear the console screen
true
370707f5da6c457ed71bbf830892dd9b6a3cc48f
Kosyka/Learning-python
/inventary2.py
2,214
4.21875
4
#Продолжение изучения кортежа inventary = ( "Меч", "Щит", "Кольчуга", "зелье лечения" ) print("В вашем распоряжении: ") for item in inventary: print(item) input("Для того, чтобы узнать размер вашего инвентаря нажмите Enter...") print("Размер инвентаря: {0} предмета/ов".format(len(inventary))) #проверка на принодлежность кортежу word = input("Введите предмет, который вы ищите (из инвентаря): \n") if word in inventary: print("Да, у вас есть такой предмет!") else: print("У вас такого предмета нет!") print(""" Выберите один из элементов инвентаря: --0---1------2---------3-------- |{0}|{1}|{2}|{3}| -------------------------------- -4 -3 -2 -1 """.format(inventary[0],inventary[1],inventary[2],inventary[3])) items = int(input()) if (items > 4) or (items < -4): print("Таких предметов нет!") else: print("вы выбрали: {0}, хороший выбор !".format(inventary[items])) input("Введите Enter...") #Практикуем срезы start = int(input("Введите начальный индекс среза: \n")) finish = int(input("Введите конечный индекс среза: \n")) print("Вы выбрали [{0}:{1}], что соотвествует элементам: \n".format(start, finish)) print(inventary[start:finish]) input("Для продолжение жмякайте Enter...") # Объединение кортежей loot = ( # Кортеж, в котором находится добытый лут героя "Золото", "Браслет", "Кольцо" ) print("Вы нашли лорец, в нем находится: {0}. Желаете забрать лут? (да\нет)".format(loot)) answer = input() if answer != "нет": inventary += loot print("Ваш инвентарь: {0}".format(inventary)) input("\n Чтобы закрыть программу, нажмите Enter...")
false
24b22a11d42fe928633529bdc3f9c7fdc7cf7003
nickaroot/pdsm04
/ex00/benchmark.py
1,187
4.21875
4
#!/usr/bin/env python3 import timeit def loop(emails): gmails_loop = [] for email in emails: if "@gmail.com" in email: gmails_loop.append(email) def comprehension(emails): [email for email in emails] def main(): emails = ['john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', 'anna@live.com', 'philipp@gmail.com', 'john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', 'anna@live.com', 'philipp@gmail.com', 'john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', 'anna@live.com', 'philipp@gmail.com', 'john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', 'anna@live.com', 'philipp@gmail.com', 'john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', 'anna@live.com', 'philipp@gmail.com'] number_of_calls = 90000000 loop_time = timeit.timeit(stmt=f"loop({emails})", setup="from __main__ import loop", number=number_of_calls) comprehension_time = timeit.timeit(stmt=f"comprehension({emails})", setup="from __main__ import comprehension", number=number_of_calls) if comprehension_time <= loop_time: print("it is better to use a list comprehension") print(f"{comprehension_time} vs {loop_time}") else: print("it is better to use a loop") print(f"{loop_time} vs {comprehension_time}") if __name__ == '__main__': main()
false
0d6a271fc3ee12c49765632be2e35ca706029e8b
premkrish/Python
/Lists/lists.py
792
4.28125
4
""" This script contains lessons for list """ #Instantitate a list list1 = [1, 2, 3, 4, 5] print(list1) list2 = [6, 7, 8, 9, 10] print(list2) #concatenation - maintains order print(f"List 1 + List 2: {list1 + list2}") print(f"List 2 + List 1: {list2 + list1}") #Add item to list list1.append(6) print(type(list1)) print(list1) #insert element at a given index list1.insert(2, 25) list1.insert(0, 34) print(list1) #Sort List list1.sort() print(list1) #Reverse list list1.reverse() print(list1) #Count no of times an element appears list1 = [3, 4, 6, 6, 5, 2, 1] print(list1.count(26)) #pop - removes element from the last print(list1.pop()) #remove - removes first occurence of a value list1.remove(6) print(list1) #clear - clears all elements of the list list1.clear() print(list1)
true
2138d7d5205c8623fea526c66a778527935381ff
premkrish/Python
/Tuples/tuples.py
1,478
4.65625
5
""" This script contains lessons for tuples """ # List and Tuple have similar features list1 = [1, 2, 3, 4, 5, 6] tuple1 = (1, 2, 3, 4, 5, 6) print(f"Length of list : {len(list1)}") print(f"Length of tuple : {len(tuple1)}") #Iterate and print the elements for n in list1: print(f"List element: {n}") print(80*"-") for n in tuple1: print(f"Tuple element: {n}") #Tuple's are smaller in size when compared to list import sys print(f"Size of List: {sys.getsizeof(list1)}") print(f"Size of Tuple: {sys.getsizeof(tuple1)}") #Tuples are immutable - cannot add/edit/delete elements once tuple is created import timeit list_time = timeit.timeit(stmt= "[1, 2, 3, 4, 5]",number=100000) tuple_time = timeit.timeit(stmt="(1,2,3,4,5)",number=100000) print(f"Time taken to create 1 million list : {list_time}") print(f"Time taken to create 1 million tuples : {tuple_time}") #Alternative ways to create tuple test1 = 1 test2 = 1,2 test3 = 1,2,3 print(test1) print(test2) print(test3) #Adding a comma after a single element would make it as a tuple test1 = 1, print(test1) #Ways to retrieve elements from tuple user_tuple = (100, "premkumar", "krishnankutty") userid = user_tuple[0] fname = user_tuple[1] lname =user_tuple[2] print(f"User Id: {userid}") print(f"First name: {fname}") print(f"Last name: {lname}") user_tuple2 = (200,"prem","krish") userid2,fname2,lname2 = user_tuple2 print(f"User Id: {userid2}") print(f"First name: {fname2}") print(f"Last name: {lname2}")
true
13825f7e72fc4ad98b21b7179eda599a15922ee1
ayush0477/pythonexperimt-
/squireelplay.py
275
4.125
4
temp = int(input("enter the temparure value\n")) summer = str(input("enter the summer value true or false\n")) if(temp>=60 and temp<=90 and summer=="false"): print("true") elif (temp>=60 and temp<=100 and summer=="true"): print("true") else: print("false")
true
98c4df06481581947e415593a11f16e435cdfbd5
realDashDash/SC1003
/Week4/Discussion2.py
1,182
4.125
4
# requirements: # - more than 8 characters # - at least one upper letter and lower letter # - at least one number # - at least one special character # todo regular expression operations def check_pw(password): length = 0 upper = False lower = False number = False special = False notValid = False Special_char = ['@', '#', '$', '^', '&', '*'] length = len(password) for ch in password: if (ord(ch) >= 97 and ord(ch) <= 122): # if (password.islower():) lower = True elif (ord(ch) >= 65 and ord(ch) <= 90): # if (password.isupper():) upper = True elif (ord(ch) >= 48 and ord(ch) <= 57): # if (password.isdigit():) number = True elif (ch in Special_char): # if(not password.isalnum) special = True else: notValid = True if (length >= 8 and upper and lower and number and special and notValid): return True else: return False while (True): pw = input("Please enter password: ") if (check_pw(pw)): print("Success!") break; else: print("Please enter another password!")
true
d29015ed62d062d408f27fed846ec277be23c029
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/w3_If_elif_Divisibilidad.py
902
4.53125
5
#Write a program which asks the user to enter a positive integer 'n' (Assume that the user always enters a positive integer) and based on the following conditions, prints the appropriate results exactly as shown in the following format (as highlighted in yellow). #when 'n' is divisible by both 2 and 3 (for example 12), then your program should print #BOTH #when 'n' is divisible by only one of the numbers i.e divisible by 2 but not divisible by 3 (for example 8), or divisible by 3 but not divisible by 2 (for example 9), your program should print #ONE #when 'n' is neither divisible by 2 nor divisible by 3 (for example 25), your program should print #NEITHER numero = input("Enter the number: ") numero = int(numero) if numero % 2 == 0 and numero % 3 == 0: print('BOTH') elif numero % 2 == 0 or numero % 3 == 0: print('ONE') elif numero % 2 != 0 or numero % 3 != 0: print('NEITHER')
true
012b37666aeb11b42bbf9deeae22a432b62760fa
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Dictionary_Assignment3_find_word_crossword_vertical.py
1,700
4.1875
4
# Part 2: Find a word in a crossword (Horizontal) # 0.0/30.0 puntos (calificados) # Write a function named find_word_vertical that accepts a 2-dimensional list of characters (like a crossword puzzle) and a string (word) as input arguments. This function searches the columns of the 2d list to find a match for the word. If a match is found, this functions returns a list containing row index and column index of the start of the match, otherwise it returns the value None (no quotations). # # For example if the function is called as shown below: # crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']] # word='cat' # find_word_horizontal(crosswords,word) # then your function should return # [1,0] # Notice that the 2d input list represents a 2d crossword and the starting index of the horizontal word 'cat' is [2,1] # # s d o g # c u c m # a c a t # t e t k # Note: In case of multiple matches only return the match with lower row index. If you find two matches in the same row then return the match with lower column index. # def find_word_vertical(crosswords,word): l=[] for i in range(len(crosswords[0])): l.append(''.join([row[i] for row in crosswords])) for line in l: #print(line) if word in line: row_index=i column_index=line.index(word[0]) #print([column_index,row_index]) return [column_index,row_index] # OJO SOLO LA FUNCION!!! # Main Program # crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']] word='cat' evalua_find_word_vertical = find_word_vertical(crosswords,word) print(evalua_find_word_vertical)
true
59035219f7287bd7c84007bdc04021f5a2a2b253
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_lider_espacio_blanco.py
614
4.3125
4
# Write a function that accepts an input string consisting of alphabetic characters and removes all the leading whitespace of the string and returns it without using .strip(). For example if: # # input_string = " Hello " # then your function should return a string such as: # output_string = "Hello " # def funcion_lider_espacio_blanco(caracteres): resume=caracteres.replace(" ","") return resume # OJO SOLO FUNCION!!! # Main Program # caracteres = str(input("Enter string: ")) evalua_funcion_lider_espacio_blanco = funcion_lider_espacio_blanco(caracteres) print(evalua_funcion_lider_espacio_blanco)
true
874b4d47c1487bdae79ec5aa4fe35402a0eff88d
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/w3_Condicional_If_elif_numero.py
467
4.3125
4
#Write a program which asks the user to type an integer. #If the number is 2 then the program should print "two", #If the number is 3 then the program should print "three", #If the number is 5 then the program should print "five", #Otherwise it should print "other". numero = input("Insert the number: ") numero = int(numero) if numero == 2: print("two") elif numero == 3: print("three") elif numero == 5: print("five") else: print("other")
true
6f94acdd9baac844cb8633d85502c84bed331182
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_suma_codigo_caracteres.py
574
4.46875
4
#Write a function that accepts an alphabetic string and returns an integer which is the sum of all the UTF-8 codes of the character in that string. For example if the input string is "hello" then your function should return 532 # def funcion_suma_codigo_caracteres(caracteres): suma=0 for x in caracteres: suma=suma+int(ord(x)) return suma # OJO SOLO FUNCION!!! # Main Program # caracteres = str(input("Enter characters: ")) evalua_funcion_suma_codigo_caracteres = funcion_suma_codigo_caracteres(caracteres) print(evalua_funcion_suma_codigo_caracteres)
true
5b6e4eca927532afdf680a6d524f5b7002940e15
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/w3_Condicional_If_elif.py
496
4.34375
4
#Ask the user to type a string #Print "Dog" if the word "dog" exist in the input string #Print "Cat" if the word "cat" exist in the input string. #(if bothj "dog" and "cat" exist in the input string, then you should only print "Dog") #Otherwise print "None". (pay attention to capitalization) cadena = input("Insert the string: ") if "dog" in cadena: print("Dog") elif "cat" in cadena: print("Cat") elif "cat" in cadena and "dog" in cadena: print("Dog") else: print("None")
true
b3f54800bd3faaee42ceb1cdf76c8d029f18bbbe
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W4_While_Calculo_Serie_3_n.py
269
4.15625
4
#Write a program using while loop, which prints the sum of every third numbers from 1 to 1001 ( both 1 and 1001 are included) #(1 + 4 + 7 + 10 + ....) numero = int(1) suma = int(0) while numero <= 1001: suma = suma + numero numero = numero + 3 print(int(suma))
true
f34ceee60cc001952bec5a15b56089be0ff2eb5f
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_E7_conteo_caracter_comun.py
1,055
4.125
4
# Write a function that takes a string consisting of alphabetic characters as input argument and returns the lower case of the most common character. Ignore white spaces i.e. Do not count any white space as a character. Note that capitalization does not matter here i.e. that a lower case character is equal to a upper case character. In case of a tie between certain characters return the last character that has the most count # def funcion_conteo_caracter_comun(input_string): input_string = input_string.lower() input_string = input_string.replace(" ","") sample_character = None sample_maximum_count = 0 for x in input_string: cont_letra = input_string.count(x) if cont_letra >= sample_maximum_count: sample_maximum_count = cont_letra sample_character = x return sample_character # OJO SOLO FUNCION!!! # Main Program # input_string = "mi hijo bruno es un niño bueno" evalua_funcion_conteo_caracter_comun = funcion_conteo_caracter_comun(input_string) print(evalua_funcion_conteo_caracter_comun)
true
f121606b3c62d6bbf0a5bc792bcf28ce2f9744a1
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W6_Strings_entero_a_caracter.py
358
4.15625
4
# Write a function that accepts a positive integer n and returns the ascii character associated with it. # def funcion_entero_a_caracter(number): return (chr(number)) # OJO SOLO FUNCION!!! # Main Program # number = int(input("Enter number: ")) evalua_funcion_entero_a_caracter = funcion_entero_a_caracter(number) print(evalua_funcion_entero_a_caracter)
true
97269d02b35e0cefd0fb906d9d58207356c07d71
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Multidimensional_E9_Function_lista_2d_to_1d.py
560
4.25
4
# Write a function that accepts a 2-dimensional list of integers, and returns a sorted (ascending order) 1-Dimensional list containing all the integers from the original 2-dimensional list. # def list_covert_2d_to_1d_list(lista): new_list = [] for data in lista: new_list=new_list+data new_list.sort() return new_list # OJO SOLO LA FUNCION!!! # Main Program # lista = [[0, 2, 4, 6, 8, 10], [11, 18, 19, 110, 111, 112]] evalua_list_covert_2d_to_1d_list = list_covert_2d_to_1d_list(lista) print(evalua_list_covert_2d_to_1d_list)
true
d779832ff8ae87018cebf243c57b5a6b3a9e0e20
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Multidimensional_E1_Function_suma_lista_2d.py
562
4.15625
4
# Write a function which accepts a 2D list of numbers and returns the sum of all the number in the list You can assume that the number of columns in each row is the same. (Do not use python's built-in sum() function). # def sum_of_2d_list(lista): total_sum=0 for data in lista: for list_index in range(0,len(data)): total_sum=total_sum+data[list_index] return total_sum # OJO SOLO LA FUNCION!!! # Main Program # lista = [[1,2,3,4],[4,3,2,1]] evalua_sum_of_2d_list = sum_of_2d_list(lista) print(evalua_sum_of_2d_list)
true
29f5308510497013c9adb03646a89d47ff5578cf
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Multidimensional_E11_Function_verifica_multiplicacion_2_matrices.py
1,075
4.4375
4
# Write a function that accepts two (matrices) 2 dimensional lists a and b of unknown lengths and returns True if they can be multiplied together False otherwise. Hint: Two matrices a and b can be multiplied together only if the number of columns of the first matrix(a) is the same as the number of rows of the second matrix(b). The input for this function will be two 2 Dimensional lists. For example if the input lists are: # # a = [[2, 3, 4], [3, 4, 5]] # b = [[4, -3, 12], [1, 1, 5], [1, 3, 2]] # Then your function should return a boolean value: # True # def check_multiplication_2_matrices(matrix_a,matrix_b): new_list = [] filas=len(matrix_a[0]) for columns in matrix_b: columnas=len(matrix_b[0]) if filas==columnas: return True else: return False # OJO SOLO LA FUNCION!!! # Main Program # matrix_a = [[2, 3, 4], [3, 4, 5]] matrix_b = [[4, -3, 12], [1, 1, 5], [1, 3, 2]] evalua_check_multiplication_2_matrices = check_multiplication_2_matrices(matrix_a,matrix_b) print(evalua_check_multiplication_2_matrices)
true
201e75cd77d36941fe1f29ffbfda2e1933a3741c
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W8_Q6_E5_Function_calculo_gastos.py
2,146
4.125
4
# Quiz 6, Part 5 # 0.0/20.0 puntos (calificados) # Write a function named calculate_expenses that receives a filename as argument. The file contains the information about a person's expenses on items. Your function should return a list of tuples sorted based on the name of the items. Each tuple consists of the name of the item and total expense of that item as shown below: # # milk,2.35 # bread , 1.95 # chips , 2.54 # milk , 2.38 # milk,2.31 # bread, 1.90 # # # Notice that each line of the file only includes an item and the purchase price of that item separated by a comma. There may be spaces before or after the item or the price. Then your function should read the file and return a list of tuples such as: # [('bread', '$3.85'), ('chips', '$2.54'), ('milk', '$7.04')] # Notes: # Tuples are sorted based on the item names i.e. bread comes before chips which comes before milk. # The total expenses are strings which start with a $ and they have two digits of accuracy after the decimal point. # Hint: Use "${:.2f}" to properly create and format strings for the total expenses. # # Please read the "File I/O Exercise Notes" before you attempt to write code. # def calculate_expenses(filename): # Make a connection to the file file_pointer = open(filename, 'r') # You can use either .read() or .readline() or .readlines() data = file_pointer.readlines() # NOW CONTINUE YOUR CODE FROM HERE!!! my_dictionary = {} for line in data: line = line.strip().split(',') my_item = line[0].strip() my_price = float(line[1].strip()) if my_item not in my_dictionary: my_dictionary[my_item] = my_price else: my_dictionary[my_item] += my_price my_list = [] my_keys = sorted(my_dictionary.keys()) for x in my_keys: my_list.append((x,"${0:.2f}".format(my_dictionary[x]))) return my_list # OJO SOLO LA FUNCION!!! # Main Program # # El archivo7.txt contiene el formato solicitado filename='archivo7.txt' evalua_calculate_expenses = calculate_expenses(filename) print(evalua_calculate_expenses)
true
23d2e251b59414149095c587cf28b660fedaf6c8
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Dictionary_E5_Function_diccionario_conteo_letras.py
937
4.375
4
# Write a function that takes a string as input argument and returns a dictionary of letter counts i.e. the keys of this dictionary should be individual letters and the values should be the total count of those letters. You should ignore white spaces and they should not be counted as a character. Also note that a small letter character is equal to a capital letter character. # def dictionary_letter_count(sample_string): sample_string=sample_string.lower() sample_string=sample_string.replace(" ","") dictionary = {} for letra in sample_string: #conteo = sample_string.count(letra) #dictionary[letra] = conteo dictionary[letra] = sample_string.count(letra) return dictionary # OJO SOLO LA FUNCION!!! # Main Program # sample_string = 'Esta es una prueba para conteo de letras' evalua_dictionary_letter_count = dictionary_letter_count(sample_string) print(evalua_dictionary_letter_count)
true
f148a68aacfd6a6803837740053704716887b4f3
ivanromanv/manuales
/Python/DataCamp/Intermediate Python for Data Science/Excercises/E3_Line plot (3).py
906
4.34375
4
# Now that you've built your first line plot, let's start working on the data that professor Hans Rosling used to build his beautiful bubble chart. It was collected in 2007. Two lists are available for you: # * life_exp which contains the life expectancy for each country and # * gdp_cap, which contains the GDP per capita (i.e. per person) for each country expressed in US Dollars. # GDP stands for Gross Domestic Product. It basically represents the size of the economy of a country. Divide this by the population and you get the GDP per capita. # matplotlib.pyplot is already imported as plt, so you can get started straight away. # # Print the last item of gdp_cap and life_exp # print(gdp_cap[-1]) print(life_exp[-1]) # Import matplotlib.pyplot as plt import matplotlib.pyplot as plt # Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis plt.plot(gdp_cap,life_exp) # Display the plot plt.show()
true
89cf8a303d3b91925367105dab6cf8b7736be519
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W7_Dictionary_E2_Function_valores_ordenados.py
528
4.3125
4
# Write a function that accepts a dictionary as input and returns a sorted list of all the values in the dictionary. Assume that the values of this dictionary are just integers. # def dictionary_sorted_values(dictionary): valores = dictionary.values() valores = list(valores) valores.sort() return valores # OJO SOLO LA FUNCION!!! # Main Program # dictionary = {'James': 19, 'Tina': 35, 'Sam': 17} evalua_dictionary_sorted_values = dictionary_sorted_values(dictionary) print(evalua_dictionary_sorted_values)
true
7a7b17926e7c5bd5c88899374ae5deb1938d0c73
YuKaoriGenji/AlgorithmExp
/AlgorithmCourse/Exp1/quicktest.py
2,901
4.21875
4
import quicksort import random import numpy as np import time def random_int_list(start,stop,length): start,stop=(int(start),int(stop)) if start<= stop else (int(stop),int(start)) length=int(abs(length)) if length else 0 random_list=[] for i in range(length): random_list.append(random.randint(start,stop)) return random_list arr=[1,4,2,3,6,6,43,6,8,45,3,1,53,7,45,3,64,7,10000,999999,44,2,8,5,3,7] print("example initial array:\n",arr) quicksort.QuickSort(arr,0,len(arr)-1) print("example result array:\n",arr) arr1=random_int_list(1,1000000,length=1000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("さあ、ゲームが始めよ!") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("終わりましたよ\__嘘です!びっくりした?") time_end=time.time() print("running time= ",time_end-time_start,'s') arr1=random_int_list(1,1000000,length=10000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("さあ、ゲームが続けよ!") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("しばらくお休みをしてくださいませ") time_end=time.time() print("running time= ",time_end-time_start,'s') arr1=random_int_list(1,1000000,length=50000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("未だ未だ続けてるよ!") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("終わりませんけどね") time_end=time.time() print("running time= ",time_end-time_start,'s') arr1=random_int_list(1,1000000,length=100000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("つづき") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("中断します") time_end=time.time() print("running time= ",time_end-time_start,'s') arr1=random_int_list(1,1000000,length=200000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("さあ、ゲームが始めよ! それはただの繰り返す") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("もうはや") time_end=time.time() print("running time= ",time_end-time_start,'s') arr1=random_int_list(1,1000000,length=500000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("さあ、ゲームが始めよ! それはただの繰り返す") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("しばらくお待ちください") time_end=time.time() print("running time= ",time_end-time_start,'s') arr1=random_int_list(1,1000000,length=1000000) #print("initial array next\n",arr1) print("array's size",len(arr1)) print("夢の始める場所!") time_start=time.time() quicksort.QuickSort(arr1,0,len(arr1)-1) print("終わりましたよ!それは本間") time_end=time.time() print("running time= ",time_end-time_start,'s')
false
ec15200763c8c79bbfc9727c1585ef8dd6292dee
dsementsov/python.cousrse.mitx
/week2_GuessMyNumber.py
828
4.15625
4
# guess my number def guess_my_number (): guess_low = 0 guess_high = 100 print ("Please think of a number between " + str(guess_low) + " and " + str(guess_high) + "!") while True: guess = int((guess_high + guess_low)/2) print("Is your secret number " + str(guess) + "?") guess_direction = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if guess_direction == "h": guess_high = guess elif guess_direction == "l": guess_low = guess elif guess_direction == "c": print("Game over. Your secret number was: " + str(guess)) break else: print("Sorry, I did not understand your input.") guess_my_number()
true
aed3fe6169903e52cd3dbe967eb88ca6690df98a
rpyne97/Code_Academy_worth_saving
/hammingsdistance.py
1,201
4.21875
4
# Input: Strings Pattern and Text along with an integer d # Output: A list containing all starting positions where Pattern appears as a substring of Text with at most d mismatches # This function matches a Pattern sequence to a Test sequence if there are less than or equal to d mismatches def ApproximatePatternMatching(Text, Pattern, d): positions = [] n = len(Text) k = len(Pattern) # range is the length of the text minus the k-mer length plus 1 for i in range(n - k + 1): # subroutine HammingDistance function # change arguments to match a k-mer pattern against a string instead of a single letter # Basically, slide Pattern across Text and append distance = HammingDistance((Pattern), (Text[i:i + k])) if distance <= d: positions.append(i) return positions # Input: Two strings p and q # Output: An integer value representing the Hamming Distance between p and q. def HammingDistance(p, q): count = 0 for i in range(len(p)): if p[i] != q[i]: count += 1 return count # Print the hamming distance (number of mismatches in two strings) represented here by variable count print(count)
true
66707f02425519ff3d9c877c0e9099da17f7a393
tgaborit/surlyllabe
/python/syllabation_encoder.py
886
4.3125
4
# -*-coding:Utf-8 -* """ Programme réalisant la syllabisation d'un mot passé en paramètre, puis encode le résultat pour donner un nombre dont les chiffres correspondent à la taille des syllabes du mot. """ import argparse from syllabes import * # Gestion des arguments parser = argparse.ArgumentParser(description="Proceeds to the syllabation of \ the word given, then encodes the result in a number whose Nth digit means \ the number of characters in the Nth syllable.") parser.add_argument("word", type=str, help="word to analyse") args = parser.parse_args() # Encodage de la syllabisation : # La chaîne du code est un nombre dont les chiffres correspondent à la taille # des syllabes, à leur position respective. ret_value = "" for syllabe in syllabation(args.word): ret_value += str(len(syllabe)) # Affichage du code sur la sortie standard print(ret_value)
false
0d24c54ddad66895ed31c0f3da5639350d25fe92
jhammelman/HSSP_Python
/lesson2/text_adventure_game.py
1,283
4.15625
4
#!/usr/bin/env python print("You are standing in front of a black iron gate with rusty hinges and a large gold lock. Behind the gate stands an ominous castle, shrouded with clouds and with large gargoyles that cast creepy shadows onto the ground.") go_in = raw_input("Do you try to open the gate? (y or n) ") if go_in == "y": print("You yank on the gate, but the large gold lock won't budge.") pick_lock = raw_input("Do you try to pick the lock? (y or n) ") # enter your if statement here to decide what happens if you try to pick the lock print("What happens? You decide...") elif go_in == "n": direction = raw_input("You decide to go home, but you've forgotten the way! Do you go left, right, or straight? (left,right,straight) ") if direction == "left": # enter your code here to continue the story print("What happens? You decide...") elif direction == "right": # enter your code here to continue the story print("What happens? You decide...") elif direction == "straight": # enter your code here to continue the story print("What happens? You decide...") else: print("Invalid input! You can't play :p") else: print("Invalid input! You can't play :p") print("The End")
true
a0b9298f53a17f612aabfaab15c89b1f72ee58d8
jupiterorbita/python_stack
/python_OOP/bike.py
1,939
4.75
5
#http://learn.codingdojo.com/m/72/5471/35330 #Assignment: Bike # Create a new class called Bike with the following properties/attributes: # price # max_speed # miles # Create 3 instances of the Bike class. # Use the __init__() method to specify the price and max_speed of each instance (e.g. bike1 = Bike(200, "25mph"); In the __init__(), also write the code so that the initial miles is set to be 0 whenever a new instance is created. # Add the following methods to this class # displayInfo() - have this method display the bike's price, maximum speed, and the total miles. # ride() - have it display "Riding" on the screen and increase the total miles ridden by 10 # reverse() - have it display "Reversing" on the screen and decrease the total miles ridden by 5... # Have the first instance ride three times, reverse once and have it displayInfo(). Have the second instance ride twice, reverse twice and have it displayInfo(). Have the third instance reverse three times and displayInfo(). # What would you do to prevent the instance from having negative miles? # Which methods can return self in order to allow chaining methods? class bike: def __init__(self, o_price=0, max_speed=0, miles=0): self.price = o_price self.max_speed = max_speed self.miles = miles def displayinfo(self): print(self.price) print(self.max_speed) print(self.miles) return self def ride(self): print('riding') self.miles += 10 return self def reverse(self): print('reversing') self.miles -= 5 return self instance1 = bike() #ride 3 times, rev once ) instance1.ride().ride().ride().reverse().displayinfo() instance2 = bike() instance2.ride().ride().reverse().reverse().displayinfo() instance3 = bike() instance3.reverse().reverse().reverse().displayinfo() # bike.displayinfo(123,123,123) # or # instance1.displayinf(123,123,123)
true
ce7d0ffa978ce9565290d9b901958bad5b5b3e8c
jupiterorbita/python_stack
/python_fundamentals/functions_interm_II_dict.py
890
4.125
4
# Assignment: Functions Intermediate II # Write the following function. # Part I (essential) # Given the following list: # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'}, # {'first_name' : 'Mark', 'last_name' : 'Guillen'}, # {'first_name' : 'KB', 'last_name' : 'Tonel'} # ] # Create a program that outputs: # Michael Jordan # John Rosales # Mark Guillen # KB Tonel students = [ {'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'}, {'first_name': 'Mark', 'last_name': 'Guillen'}, {'first_name': 'KB', 'last_name': 'Tonel'} ] def dictfunction(): for i in range(len(students)): print(i+1,' - ',students[i]['first_name'], students[i]['last_name'], ' - ', ((len(students[i]['first_name']))+(len(students[i]['last_name'])))) dictfunction()
false
db273d324cceae6725e9b753373f78d5d9ea007d
BrodyJorgensen/practicles
/prac_1/loops.py
480
4.28125
4
#for the odd numbers #for i in range(1, 21, 2): # print(i) #count to 100 in lots of 10 #for i in range(0, 101, 10): # print(i) #to ocunt down from 20 #for i in range(20, 0, -1): # print(i) #printing different numbers of stars #number_of_stars = int(input("Number of stars: ")) #for i in range (number_of_stars): # print('*') #increasing stars being printed number_of_stars = int(input("Number of stars: ")) for i in range(1, number_of_stars + 1): print('*' *i)
true
19da8c81fbbbde3d9e08038825566210a88ff341
AlexFue/Interview-Practice-Problems
/math/fizz_buzz.py
1,102
4.4375
4
# Problem: # Given an input, print all numbers up to and including that input, unless they are divisible by 3, then print "fizz" instead, or if they are divisible by 5, print "buzz". If the number is divisible by both, print "fizzbuzz". # For example, given 5: # 1 # 2 # fizz # 4 # buzz # Given 10: # 1 # 2 # fizz # 4 # buzz # fizz # 7 # 8 # fizz # buzz # Given 15: # 1 # 2 # fizz # 4 # buzz # fizz # 7 # 8 # fizz # buzz # 11 # fizz # 13 # 14 # fizzbuzz # Solution: def fizzbuzz(n): for x in range(1, n+1): if x % 3 == 0 and x % 5 == 0: print('fizzbuzz') elif x % 3 == 0: print('fizz') elif x % 5 == 0: print('buzz') else: print(x) # process: #input: 15 #start at 1 and go all the way to 15 #1 - not div by 3, 5, or both, so print : 1 #2 - not div by 3, 5, or both, so print : 2 #3 - not div by 5, both, but div by 3 so print: fizz #4 - not div by 3, 5, or both, so print : 4 #5 - not div by 3, both, but div by 5 so print : buzz #15 - div by 3, 5, and both so print : fizzbuzz
true
c0bbf25f0855f258bc7bec174de3e3fb607eee64
AlexFue/Interview-Practice-Problems
/math/palindrome_number.py
2,054
4.3125
4
Problem: Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Could you solve it without converting the integer to a string? Example 1: Input: x = 121 Output: true Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Example 4: Input: x = -101 Output: false Constraints: -231 <= x <= 231 - 1 Solution: class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False multiplier = 1 # variable to check ends while x / multiplier >= 10: # will increment the variable to be the same length as x multiplier *= 10 while multiplier >= 10: # do this while our variable can check more than 1 number if x // multiplier != x % 10: return False # if the ends of x are not equal, return false x = (x % multiplier) // 10 # the modulo deletes the front end of x and takes off any leading zeros, and the division takes up the end of x multiplier = multiplier // 100 # shaves off 2 zero places from variable since we shaved off 2 nunmbers off x return True # if we went through whole number x and they ends were all the same, return x Process: The way we solve this problem is with math. The way the algorithm goes for this problem is that if we compare the front half of the number to the back half, then we can check if its a palindrome without having to go through the whole thing. To make this easier, we can get rid of the negative numbers since the - sign makes it not a palindome any more. We need another variable to let us do math and check each side of the number to see if they are equal, if so then we delete it and update our variables to check the next ends of the number.
true
256a03dcbc7e21268fcac16009241ae548e22f5a
AlexFue/Interview-Practice-Problems
/string/group_anagrams.py
1,935
4.4375
4
Problem: Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] Solution: class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = {} for s in strs: l = ''.join(sorted(s)) if l in d: d[l] += [s] else: d[l] = [s] return [g for g in d.values()] Process: The way we are going to solve this problem is with a dictionary We create a dictionary to store all the groups of anagrams. Basically we loop through each string in the strs list, and we sort each string in a variable. We do this so we can use the it as a key in the dictionary, and have the anagram groups as the values. This is an easier way to check if a string belongs into a group. And if there is no group for it, we can make one. You may wonder wonder why we insert the sorted string in a set of []. well this keeps the elements of the string together becaue without it, the characters of the string are seperated. 1.) Dictionary: - to store anagram groups and sort them. 2.) Loop through the strs list: a.) Sort the current string into a variable to use it as a key in the dictionary b.) check if the sorted string group is already in the dictionary - if it is then add the nonsorted string into the group c.) if not then create a group for it and add the nonsorted string 3.) loop through the values of the dictionary and add them into one list to return
true
4bb9c049136e21b22c9ed3047e55559d766d8051
AlexFue/Interview-Practice-Problems
/math/power_of_three.py
688
4.6875
5
Problem: Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Solution: import math def power_of_three(n): power = 0 while 3**power <= n: if 3**power == n: return True power += 1 return False Process: varible power that represents the power of 3 and starts at 0 while 3**power <= n #does this while the power of 3 is under n if 3**power == n #checks if it is a power of three return true power +=1 #increments to check if the next power is under n outside the while loop return false
true
f396cb3f64cc487ad75d3c5d2cceb84ccd7b1b00
AlexFue/Interview-Practice-Problems
/sorting_algorithm/median_two_sorted_arrays.py
2,137
4.15625
4
Problem: Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. Follow up: The overall run time complexity should be O(log (m+n)). Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. Example 3: Input: nums1 = [0,0], nums2 = [0,0] Output: 0.00000 Example 4: Input: nums1 = [], nums2 = [1] Output: 1.00000 Example 5: Input: nums1 = [2], nums2 = [] Output: 2.00000 Solution: class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: if not nums1 and not nums2: return 0 if len(nums1) == 1 and len(nums2) == 0: return nums1[0] if len(nums1) == 0 and len(nums2) == 1: return nums2[0] nums1 = nums1 + nums2 nums1.sort() if len(nums1) % 2 == 0: return (nums1[(len(nums1)//2)] + nums1[(len(nums1)//2-1)]) / 2 else: return nums1[len(nums1)//2] Process: The way we are going to solve this is adding the list together and using a sort method. First we do some edge cases to get rid of the weird data. After we add two list together and sort it with the built in python method. Then we check if there are an odd or even amount of numbers in the list to get the median. For a even list, we get two middle numbers to get the median, while in the odd list we just get the middle number 1.) Edge cases: a.) check if one list is empty and the other is not - return a the element from the non empty list b.) do the same check base but opposite of the one before. 2.) Combine lists: a.) add both lists together to create one b.) sort the list 3.) Check if list is even or odd: a.) if list has even amount of numbers - get the 2 even numbers, add them, then divide for median and return b.) if list has odd amount of numbers - get the middle number and return it
true
69bce08cc02472e4ec62a8dfb78e586692574dfa
flashypepo/myMicropython-Examples
/displays/DisplaysDrawingText/drawtextnpmatrix.py
813
4.125
4
# 2016-1219 draw text on neopixel matrix # https://learn.adafruit.com/micropython-displays-drawing-text/software import neopixel import machine matrix = neopixel.NeoPixel(machine.Pin(13, machine.Pin.OUT), 64) # define the pixel function, which has to convert a 2-dimensional # X, Y location into a 1-dimensional location in the NeoPixel array... def matrix_pixel(x, y, color): matrix[y*8 + x] = color # Finally create the font class and pass it the pixel function created above... import bitmapfont bf = bitmapfont.BitmapFont(8, 8, matrix_pixel) bf.init() # Then draw some text! # tuple-color is passed to the pixel function bf.text('A', 0, 0, (64, 0, 64)) # Peter: I must write the text-buffer to the neopixel matrix! matrix.write() width = bf.width('A') print('A is {} pixels wide.'.format(width))
true
64291a7cb59c8e4de148a075ab0c0f59faf84b84
BlueBookBar/SchoolProjects
/Projects/PythonProjects/Project4.py
1,825
4.125
4
#used the factorial number system def Permutation(thisList): NumberofpossibleFactorial = [1]#Used to contain the number of factorial possiblities of the permutation for iterator in range(1,len(thisList)+1):#Populate the factorial list NumberofpossibleFactorial.append(NumberofpossibleFactorial[iterator-1]*iterator)# [1, 1, 2, 6, 24...] for iterator in range(0, NumberofpossibleFactorial[len(thisList)]):#Go loop through as many times as the factorial NewPermutationList = ""#Will hold the new permutation list OldPermutationList = str(thisList)#Will hold the old permutation list outerPosition = iterator for innerPosition in range(len(thisList), 0, -1):#loops and each time moves the approriate character from OldPermutationList to NewPermutationList selectedPosition = int(outerPosition/NumberofpossibleFactorial[innerPosition-1])#Divide the OuterPosition by the NumberofpossibleFactorial NewPermutationList =NewPermutationList+ OldPermutationList[selectedPosition]#Add the character from the OldList to the new list outerPosition %= NumberofpossibleFactorial[innerPosition - 1]#move the outposition to the next spot OldPermutationList = OldPermutationList[0:selectedPosition]+ OldPermutationList[selectedPosition+1:]# Remake the old list without the removed character print(NewPermutationList)#Print out the new variation of permutation if __name__ == "__main__": lengtho=input('Enter the variable n, a list will generate based on the number entered(5 will generate list 0-4): ') lengtho = int(lengtho)# record the answer a = "" #Create the string for i in range(0, lengtho): #Populate the string with numbers 1, 2, 3... a+=str(i) Permutation(a)# call the permutation function
true
469d35e7c3c3d7dbd7ef63c65af009e1e6b764ea
qsyed/python-programs
/leetcode/reverse_integer.py
1,282
4.15625
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: def reverse(self, x: int) -> int: if x >= 2**31-1 or x <= -2**31: return 0 elif x ==0: return 0 elif x > 0: # print(type(x)) str_of_x = str(x) reversed_x = str_of_x[::-1] if reversed_x[0] == "0": return reversed_x[1:] elif reversed_x[0] != "0": return reversed_x elif x < 0: str_of_x = str(x) reversed_x = str_of_x[::-1] if reversed_x[0] == "0": take_out_zero = reversed_x[1:] delete_negative = take_out_zero[:-1] return "-" + delete_negative else: delete_negative = reversed_x[:-1] return "-" + delete_negative
true
6e9126df734b950627a21661d32c6e99ce738395
qsyed/python-programs
/sqlite3-python/sql_injection.py
1,313
4.375
4
import sqlite3 conn = sqlite3.connect("sqlite3-python/users.db") """ this execrise wa meant to show how sql injection can work if the query strings are not set up properly first we have to set up a data base and enter in seed data. the data base was created by using query = "CREATE TABLE user (username TEXT, password TEXT) " and c.execute(query I then created a list of users: list_users = [ ("Roald","password123"), ("Rosa", "abc123"), ("Henry", "12345") ] the seed data was executed by using: c.executemany("INSERT INTO user VALUES (?,?)", list_users) """ user_name = input("please enter username ") password = input("please enter password ") query = f"SELECT * FROM user WHERE username='{user_name}' and password='{password}'" c= conn.cursor() c.execute(query) result = c.fetchone() if(result): print("welcome back") else: print("user does not exist") conn.commit() conn.close() """ when using f string the query can manipulated using sql: enter a name of a user as is and to inject in password field type ' or 1=1-- the coorect way to ask a user for input is the following: query = f"SELECT * FROM user WHERE username=? and password=?" followed by c.execute(query,(user_name, password)) """
true
74d2268b7683c0da087c8c2f6e4f7549e2788998
JulieRoder/Practicals
/Activities/prac_06/car.py
1,162
4.25
4
""" CP1404/CP5632 Practical - Car class example. Student name: Julie-Anne Roder """ class Car: """Represent a Car object.""" def __init__(self, name="Car", fuel=0): """Initialise a Car instance. fuel: float, one unit of fuel drives one kilometre """ self.name = name self.fuel = fuel self.odometer = 0 def __str__(self): """Default print statement.""" return "{}, fuel={}, odometer={}".format(self.name, self.fuel, self.odometer) def add_fuel(self, amount): """Add amount to the car's fuel.""" self.fuel += amount def drive(self, distance): """Drive the car a given distance. Drive given distance if car has enough fuel or drive until fuel runs out return the distance actually driven. """ if distance > self.fuel: distance = self.fuel self.fuel = 0 else: self.fuel -= distance self.odometer += distance return distance def run_tests(): c1 = Car() c2 = Car(45) c2.name = "Van" print(c1) print(c2) if __name__ == '__main__': run_tests()
true
dc37ecb1e5a2fd133bbae234ff4f9351ba608c97
JulieRoder/Practicals
/Activities/prac_06/guitar_class.py
823
4.125
4
""" Guitar Class Student name: Julie-Anne Roder """ class Guitar: """Represents a Guitar Object.""" CURRENT_YEAR = 2020 VINTAGE_THRESHOLD = 50 def __init__(self, name="", year=0, cost=0.0): """Initialises a guitar instance name: make & model year: year guitar was made cost: guitar purchase price.""" self.name = name self.year = year self.cost = cost def __str__(self): """Default print statement - Name (Year) : Cost.""" return "{} ({}) : ${:.2f}".format(self.name, self.year, self.cost) def get_age(self): """Get age of guitar.""" return Guitar.CURRENT_YEAR - self.year def is_vintage(self): """Determine if guitar is vintage.""" return self.get_age() >= Guitar.VINTAGE_THRESHOLD
true
4fb8c17e5922581379dd0bc65e9c29e46c364a47
Jian-jobs/Jian-leetcode_python3
/algorithm/BubbleSort.py
747
4.15625
4
# coding:utf-8 # 冒泡排序 # 1. 外层循环负责帮忙递减内存循环的次数【1, len-1】 # 2. 内层循环负责前后两两比较, index 的取值范围【0, len-2】 len-1-i 次,求最大值放到最后 def bubble_sort(nums): # [1, len-1] for i in range(1, len(nums)-1): print(i) # [0, len(nums)-i] j is index for j in range(len(nums)-i): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] print(j, nums) return nums if __name__ == "__main__": nums = [2, 6, 8, 5, 4, 9, 3, 7] bubble_sort(nums) print('result is: ', nums) # reference: https://github.com/apachecn/awesome-algorithm/blob/master/src/py3.x/sort/BubbleSort.py
false
2feff85ac758dcafa3d9f7dfdc3fac2acea55acc
pastaTree/Data-Structures-and-Algorithms
/453_flatten_binary_tree_to_linked_list.py
2,020
4.1875
4
"""453 Flatten Binary Tree to Linked List Algorithm: 1. 显然我们很难直接在数上操作达到in-place的flatten 2. 使用递归 3. 把right subtree挂到left subtree的最右边节点上,left subtree再挂到root的right上去。 这样不停操作,就可以达到把树向右边flatten的目的。 Note: 分治:(返回最后一个节点) 情况 操作 返回值 左有右有 swap right_last 左有右无 swap left_last 左无右有 N/A right_last 左无右无 N/A node 前序遍历求链表:(要求掌握) 在进行self.flatten(root.left)的时候 root.right会发生改变 (在flatten root.left中 last_node是现在的root,而在flatten root.left中 last_node.right会变化,即对应现在的root.right也会发生变化) 所以要留一个临时变量存储此时的root.right值,保证在进行self.flatten(root.right)时,此时的root.right 不收到上一行的子函数self.flatten(root.left)的干扰 Complexity: O(n) """ class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten(self, root): self.flatten_linked_list(root) def flatten_linked_list(self, node): if node is None: return None left_last = self.flatten_linked_list(node.left) right_last = self.flatten_linked_list(node.right) if left_last is not None: left_last.right = node.right node.right = node.left node.left = None return right_last or left_last or node class SolutionTraversal: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ last_node = None def flatten(self, root): if root is None: return None if self.last_node is not None: self.last_node.right = root self.last_node.left = None self.last_node = root right = root.right self.flatten(root.left) self.flatten(right)
false
0ba48b9de780c8ce1add0dfdadddce69e4ce4e36
santosh235/com_phy
/HW1/santosh_HW1/3/3.py
382
4.1875
4
# Q3:TO PRINT POLAR COORDINATES import math import numpy as np x=input("Enter the X-cordinate:") y=input("\n Enter the Y-cordinate:") x=float(x) y=float(y) r=x*x+y*y r=math.sqrt(r) rad=np.arctan(abs(y)/abs(x)) theta=(360*rad)/(2*3.14) if x<0 and y>0 : theta=theta+90 if x<0 and y<0 : theta=theta+180 if x>0 and y<0 : theta=theta+270 print("R=%f" %r) print("theta=%f" %theta)
false
751627ebef789a911d50b90d2f398c6b49dbdf3d
ctostado/Python-Projects
/Ejemplos/Listas.py
618
4.21875
4
datos = [4, "Caracteres", -13, 3.1416, "otra cadena"] print (datos[0]) print (datos[3]) print (datos[0:2]) print (datos[2:]) #Añadiendo contendio a las listas pares = [0,2,4,5,8] pares[3] = 6 print(pares) pares.append(10) print(pares) pares.append(6*2) print(pares) #Modificando el contenido con Slicing letras = ['a','b','c','d','e'] #Modificando valores de un lista letras[0:3] = ['A','B','C'] print(letras) #Borrando valores de una lista letras[0:3] = [] print(letras) #Borrando toda la lista letras = [] print(letras) #Obteniendo tamaño de la listas print(len(letras)) print(len(pares))
false
9bdb46cb7f8263c67a7f8d76643ebaf4e048883b
wfhsiao/datastructures
/python/classes/LinkedQueue.py
1,510
4.375
4
# Python3 program to demonstrate linked list # based implementation of queue # A linked list (LL) node # to store a queue entry class Node: def __init__(self, data): self.data = data self.next = None # A class to represent a queue # The queue, front stores the front node # of LL and rear stores the last node of LL class Queue: def __init__(self): self.front = self.rear = None def isEmpty(self): return self.front == None # Method to add an item to the queue def enQueue(self, item): temp = Node(item) if self.rear == None: self.front = self.rear = temp return self self.rear.next = temp self.rear = temp return self # Method to remove an item from queue def deQueue(self): if self.isEmpty(): return None temp = self.front self.front = temp.next if(self.front == None): self.rear = None return temp.data def __str__(self): res=[] p = self.front first=True while p: res.append( f'{p.data}' ) p = p.next res.reverse() return '>'+', '.join(res)+'>' def __repr__(self): return self.__str__() def getFront(self): return self.front.data def getRear(self): return self.rear.data
true
0ba44ef8e4017d9152f874ef190d2b09c4c58764
jfcjlu/APER
/Python/Ch. 07. Python - Normal Distribution - Probability of x between x1 and x2.py
585
4.125
4
# Python - NORMAL DISTRIBUTION - PROBABILITY OF x BETWEEN x1 AND x2 # http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html from scipy.stats import norm # Enter the following values mean = 4 # the mean stdev = 1 # and standard deviation of the distribution # Enter the values of the limits of x: x1 = 3 x2 = 5 # Evaluation of the probability of a value of x between x1 and x2 is: p = norm.cdf(x2, mean, stdev) - norm.cdf(x1, mean, stdev) # Result: print() print("The probability of a value of x between x1 =", x1, "and x2 =", x2, "is p =", p)
true
09bae4b4fd74433d59a19694a3a7a9a0a672dbc1
shahed-swe/python_practise
/recursion.py
1,522
4.15625
4
# here we will discuss about recursion # factorial problem def factorial(n): '''this function return the factorial number''' if n == 1: return 1 return n * factorial(n-1) # out put will be the factorial of the number is given # reverse order problem def print_rev(i,n, a): '''this function basically returns your given array in reverse order and print it''' if(i < n): print_rev(i+1, n, a) print(f"{a[i]}") # Input: # 5 # 69 87 45 21 47 # Output: # 47 21 45 87 69 def printing_method(i, j, a): '''this function basically print the given array in box sequence''' if i <= j: print(f"{a[i]} {a[j]}") printing_method(i+1, j-1, a) # Input: # 5 # 1 5 7 8 9 # Output: # 1 9 # 5 8 # 7 7 # def remove_odd_int(i,j,n,a): # if(i == n): # n = j # return # if a[i] % 2 == 0: # j += 1 # a[j] = a[i] # remove_odd_int(i+1, j,n,a) # square sum def sqr_sum(n): if n == 1: return 1 return n * n + sqr_sum(n-1) if __name__ == '__main__': number = factorial(4) print(number) # for next problem list1 = [3,5,6,12,17] print_rev(0, len(list1), list1) # for next problem printing_method(0, len(list1)-1, list1) # for next problem print(sqr_sum(10)) # remove_odd_int(0,0,len(list1), list1) # for i in list1: # print(i) n = int(input('Enter a number:')) fact = 1 while n >= 1: fact = fact * n n = n - 1 print(f"Factorial: {fact}")
true
6e16b3b82f4942ed14679fa2b22e22ae527eb67e
shahed-swe/python_practise
/flexible_functions.py
2,624
4.40625
4
# intro to arguments means (args*) # make flexible function # *operator # *args def all_elem(*args): print(args) print(type(args)) def all_sum(*args): total = 0 for i in args: total += i return total if __name__ == '__main__': all_elem(2,3,4,5) print(all_sum(2,5,6,7,8,9)) #we can't write parameter after *arg def sum_multy(a,b,*args): total = 1 for i in args: total *= i return total+a+b if __name__ == '__main__': count = sum_multy(27,8,4,5,6,7,8) print(count) # *args with list def multiply_nums(*args): mul = 1 for i in args: mul *= i return mul if __name__ == '__main__': num2 = [2,3,4] print(type(multiply_nums(2,5,4))) print(type(multiply_nums(*num2))) print(multiply_nums(2,3,4)) print(multiply_nums(*num2)) #unpack the list elements first for arguments #without list comprehension def power_set(num,*args): new_list = [] for i in args: new_list.append(i**num) return new_list if __name__ == '__main__': set = [1,2,3,4,5] print(power_set(2,*set)) # with list comprehension def power_set(num,*args): if(len(args) < 1): return "no value has been given inside arguments" else: return [i**num for i in args] if __name__ =='__main__': list1 = [1,2,3,4,5,6] print(power_set(2,*list1)) # another method def power_set(num, *args): if args: return [i**num for i in args if i % 2 == 0] return "no values to unpack for calculation" if __name__ == '__main__': list1 = list(range(1,11)) print(power_set(2, *list1)) #**kwargs implementation def func(**kwargs): for i,j in kwargs.items(): print("{} : {}".format(i,j)) if __name__ == '__main__': func(name = "shahed",age = "21") #another def func(n,**kwargs): for i,j in kwargs.items(): print("{} : {}".format(i,j)) print(n) if __name__ == '__main__': func("Hello",name = "Shahed",age = "21") #dictionary unpacking def dict_unpacking(**kwargs): for i,j in kwargs.items(): print("{} : {}".format(i,j)) if __name__ == '__main__': new_dict = dict( name = "Shahed", age = "21", address = "khagan" ) print(new_dict) dict_unpacking(**new_dict) #default param def func(name = 'unknown',age = 24): print(name) print(age) func() func("shahed") func("shahed",22) # capital string def capital_str(l1,**kwargs): if kwargs.get('reverse_str') == True: return [name[::-1].title() for name in l1] else: return [name.title() for name in l1] if __name__ == '__main__': list1 = ['shahed','ashik'] print(capital_str(list1)) print(capital_str(list1, reverse_str = True))
false
62960d349418a139f2dbe16a607dbdbc2f012716
caiolucasw/pythonsolutions
/exercicio53.py
1,063
4.59375
5
'''Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, the output of the program should be: john In case of input data being supplied to the question, it should be assumed to be a console input.''' email = input('Digite um email no formato aaaa@empresa.com: ') email_lista = email.split('@') nome = email_lista[0] print(nome) #exercicio54 '''Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, the output of the program should be: google''' email = input('Digite um email no formato aaaa@empresa.com: ') email_lista = email.split('@') empresa = email_lista[1].split('.')[0] print(empresa)
true
65f418215ce8198f87b4bb9e15b1839663360cbf
caiolucasw/pythonsolutions
/exercicio31.py
268
4.1875
4
'''Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.''' dicionario = {i: i**2 for i in range(1,21)} print(dicionario) #exercicio32 for i in dicionario.keys(): print(i)
true
d020d4a32b7a6b4d62b80a73c0f3687874c79feb
Strangedip/Rock-Paper-Scissor-game
/main2.py
830
4.1875
4
#create rock paper scissor game using functions import random def gamewin(comp, player): if comp == player: return None elif comp == "r": if player=="p": return True else : return False elif comp == "p": if player=="s": return True else : return False elif comp == "s": if player=="r": return True else : return False comp = random.randint(1,3) if comp ==1: comp="r" elif comp ==2: comp="p" else: comp="s" player= input("Enter Your Choice\nRock(r), Paper(p), scissor(s) : ") print(f"The Computer Chose {comp}") a=gamewin(comp,player) if a==None: print("Its a Tie !") elif a: print("You Won !") else : print("You lose !")
false
d7726b01bddf327561c0914c1c7db68433f840b1
spacecowboy2049/clouds
/Linux/python/1/Activities/05-Variable-Dissection/UNSOLVED-Variables-Dissect.py
1,714
4.3125
4
# Part 1 # ===================================== # Prints: [FILL IN] variable_one = 10 print(variable_one) print(type(variable_one)) # Prints: [FILL IN] variable_two = 5 print(variable_two) # Prints: [FILL IN] sum_of_variables = variable_one + variable_two print(sum_of_variables) # Prints: [FILL IN] difference_of_variables = variable_one - variable_two print(difference_of_variables) # Prints: [FILL IN] division_variable = variable_one / variable_two print(division_variable) print(type(division_variable)) # Prints: [FILL IN] multiplication_variable = variable_one * variable_two print(multiplication_variable) # Part 2 # ===================================== # Prints: [FILL IN] variable_three = 1.25 print(variable_three) print(type(variable_three)) # Prints: [FILL IN] variable_sum = variable_three + 1 print(variable_sum) print(type(variable_sum)) # Part 3 # ===================================== # Prints: [FILL IN] variable_four = "This is some nifty text!" print(variable_four) print(type(variable_four)) # Prints: [FILL IN] variable_five = "This is also some sweet text!" print(variable_five) # Prints: [FILL IN] joined_vars = variable_four + " " + variable_five print(joined_vars) # Prints: [FILL IN] this_will_work = "My favorite number is " + str(14) print(this_will_work) # Prints: [FILL IN] text_int = "200" text_float = "3.1459" adding_together = int(text_int) + float(text_float) print(adding_together) # Part 4 # ===================================== # Bonus: Why will the below statement not work (if uncommented) # will_not_work = "My favorite number is " + 14 # print(will_not_work)
true
09172aacd60e7d7b00b39fffe191ccb571fe0665
brdyer/DAEN_500_Fall_2020_Final_Exam
/DAEN_500_final_prob_1.py
892
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 8 08:21:51 2020 @author: braddyer """ # get user input of range for analysis usr_range_start = int(input('Enter the low end of the range you want to try: ')) usr_range_end = int(input('Enter the high end of the range you want to try: ')) # determine the range -> add 1 to high end for inclusion usr_range = range(usr_range_start, (usr_range_end + 1)) if usr_range_start <= usr_range_end: # determine what numbers within range are divisible by 7 except those that are multiples of 5 while usr_range_start in usr_range: if usr_range_start % 7 == 0 and usr_range_start % 5 != 0: print(usr_range_start) usr_range_start += 1 else: usr_range_start += 1 # if second integer is less than the first else: print('second integer can\'t be less than the first.\n')
true
651d4ded3f2b151553b44c300998d6352c69a76e
mturpin1/CodingProjects
/Python/encrypt.py
385
4.21875
4
import os plainText = input('Please enter a word you would like encrypted - ').lower().strip() key = int(input('Please enter an encryption key (it can be any whole number) - ')) alphabet = 'abcdefghijklmnopqrstuvwxyz' encryptedText = '' for letter in plainText: index = alphabet.find(letter) encryptedText += (alphabet[(index + key) % 26]) os.system('cls') print(encryptedText)
true
b3116b23c454985cdc1c5a6c00d8e6b4123d596a
mturpin1/CodingProjects
/Python/curfew_checker.py
911
4.3125
4
age = input('How old are you?: ') age = int(age) time = input('What hour is it?: ') time = int(time) def curfew_check(): if age >= 0 and age <= 12: print('\"Get off the computer, please.\"') elif (age > 12 and age <= 16) and (time >= 0 and time <= 8): print('\"You should be asleep!\"') elif (age > 12 and age <= 16) and (time > 8 and time <= 20): print('\"You are good!\"') elif (age > 12 and age <= 16) and (time > 20 and time <= 24): print('\"Your curfew is up!\"') elif (age >= 17 and age <= 18) and (time >= 0 and time <= 6): print('\"You should be asleep!\"') elif (age >= 17 and age <= 18) and (time > 6 and time <= 22): print('\"You are good!\"') elif (age >= 17 and age <= 18) and (time > 22 and time <= 24): print('\"Your curfew is up!\"') elif age > 18: print('\"Do whatever you want!\"') curfew_check()
false
dfcc64126ae03f7328660a14a3f87cf4056416d6
mturpin1/CodingProjects
/Python/debugging3.py
340
4.28125
4
color = input('Pick a color. ') def color_choice(color): if color == 'red' or color == 'Red': print('You chose red.') elif color == 'blue' or color == 'Blue': print('You chose blue.') elif color == 'orange' or color == 'Orange': print('You chose orange.') else: print('You screwed something up.') color_choice(color)
true
7b62c3824d332f64cba621ce991237cafcc09118
SHPStudio/LearnPython
/basic/iteration.py
978
4.125
4
# 迭代器 # Iterator 可以使用next()不断获取值的对象 并且可以使用isinstance()判断对象是否是迭代器 # Iterable 是可以使用for迭代去获取值的对象 叫可迭代对象但并不一定是Iterator # 比如generater生成器一定是迭代器对象 list tuple set等等可能就不是迭代器对象 # 但是他们可以使用iter()变为迭代器对象 from collections import Iterable,Iterator print(isinstance('adfa',Iterable)) print(isinstance([1,1,2,3],Iterable)) print(isinstance((1,1,2,3),Iterable)) print(isinstance((1,1,2,3),Iterator)) print(isinstance([1,1,2,3],Iterator)) print(isinstance(iter([1,1,2,3]),Iterator)) # 为什么list tuple等等不是interator对象 # 因为像迭代器这种通过next()获取数据直到报错表示没有数据 # 也就是说他是一种懒加载数据的方式,并不知道什么时候才是头 # 也就是相当于无限数据流Interator可以存储无穷自然数 但是list这种不就可能了
false
a9042e33d9a85d4a4329f85024ffde27f0503528
haidarknightfury/PythonBeginnings
/Programs/SearchEngine/OtherPrograms/Symmetric.py
626
4.34375
4
# A list is symmetric if the first row is the same as the first column, # the second row is the same as the second column and so on. Write a # procedure, symmetric, which takes a list as input, and returns the # boolean True if the list is symmetric and False if it is not. def symmetric(lists): if lists == []: return False i = 0 m = 0 while i < len(lists): while(m < len(lists)): if lists[i][m] != lists[m][i]: return False m = m + 1 i = i + 1 return True print symmetric([[1, 2, 3], [2, 3, 4], [3, 4, 1]])
true
1e951346e8e76304a79f761ab81cbf7a5f3334b4
haidarknightfury/PythonBeginnings
/Programs/SearchEngine/OtherPrograms/IdentityMatrix.py
696
4.1875
4
# Given a list of lists representing a n * n matrix as input, # define a procedure that returns True if the input is an identity matrix # and False otherwise. # An IDENTITY matrix is a square matrix in which all the elements # on the principal/main diagonal are 1 and all the elements outside # the principal diagonal are 0. # (A square matrix is a matrix in which the number of rows # is equal to the number of columns) def is_identity_matrix(matrix): for i in range(0, len(matrix)): for j in range(0, len(matrix)): if i == j and matrix[i][j] != 1: return False elif i != j and matrix[i][j] != 0: return False return True
true
946833b6f8f89ed914ccdf9fe14b3dea226d5121
beknazar1/code-platoon-self-paced
/week-1-challenges/armstrong_numbers.py
612
4.1875
4
import math def find_armstrong_numbers(numbers): OUTPUT = [] for number in numbers: # Leverage python libraries to easily split a number into a list of digits DIGITS = [int(digit) for digit in str(number)] # Length of DIGITS list will be the exponent per defintion of Armstrong numbers power = len(DIGITS) # Leverage python again, to calculate sum of powers armstrongCandidate = sum([math.pow(digit, power) for digit in DIGITS]) if armstrongCandidate == number: OUTPUT.append(int(armstrongCandidate)) return OUTPUT
true
d42e67147a1222caeaa547d013741f55c7894669
griffithcwood/Image-Processing
/imageOpen.py
828
4.15625
4
#!/usr/bin/env from tkinter import filedialog from tkinter import * import tkinter as tk # neede for window def prompt_and_get_file_name(): """prompt the user to open a file and return the file path of the file""" # TO DO: add other file types!!!!!!!!!!!!!!!!!! try: img_file_name = filedialog.askopenfilename( initialdir = "/", title = "Select file", filetypes = ( ("jpeg files","*.jpg"), # still need jpEg!!! ("gif files", "*.gif"), ("png files", "*.png"), ("all", "*.*") ) # add more types: using tuple: ("description", "*.type") ) except: print("Image file not able to be opened") # return name of selected file as string: return img_file_name
true
72b840a1618a274cd2e076fd0a796fe2dcae79f3
Skumbatee/bc-9-oop
/student.py
2,003
4.1875
4
import datetime map_ = { 'UG': 'Uganda', 'KE': 'Kenya', 'NG': 'Nigeria', 'TZ': 'Tanzania' } class Student(object): #declaring a variable Id with a value zero which is an instance variable Id = 0 #Create an empty dictionary attendace that stores the attendance of the students attendance = {} def __init__(self, fname, lname, cc='KE'): #Increment the Student Id everytime this class is called so that everyone has a unique Id Student.Id = Student.Id + 1 self.unique_id = Student.Id self.fname = fname self.lname = lname self.country = map_[cc] def attend_class(self, **kwargs): ''' defaualt values: loc = 'Hogwarts' date = 'today' teacher = 'Alex' ''' loc = kwargs.get('loc', 'Hogwarts') date = kwargs.get('date', datetime.date.today()) teacher = kwargs.get('teacher', 'Alex') if date not in Student.attendance.keys(): #Check if each date is in the attendance list, if not, add both the current date and the full name of the student Student.attendance[date] = [self.fname + " " + self.lname] else: full_name = self.fname + " " + self.lname if full_name not in Student.attendance[date]: Student.attendance[date].append(full_name) @staticmethod def attendance_list(date): if date not in Student.attendance.keys(): #Print the records for the current date, if none, then no attendance print("No Attendance today!") else: the_attendance_list = Student.attendance[date] print("Attendance on: " + str(date)) for student in the_attendance_list: print(student)
false
25f4d99f9dd32a9ac8d5d2ddab5959822c0c932f
Dhan-shri/If-else
/schedule.py
669
4.34375
4
time=float(input("enter a time")) # time is given in 24 format if time>6 and time<=7: print("morning exercise") elif time>7 and time<=8.30: print("breakfast") elif time>8.30 and time<=9.30: print("english activity") elif time>9.30 and time<=13: print("coding time") elif time>13 and time<=14.30: print("lunch break") elif time>14.30 and time<=17: print("study") elif time>17 and time<=19: print("cultural time") elif time>19 and time<=21: print("study coding time") elif time>21 and time<=22: print("dinner time") elif (time>22 and time<=24) or (time>=1 and time<=6): print("personnel time") else: print("time is not valid")
true
710aebc04b24921c716e0c3ff0b30574773c9c68
kalu661/desafio
/desafio_1.py
1,241
4.1875
4
print('>-----------------------------------------<') #Definicion de Variables palabra = input('Ingrese una palabra '); palabra1 = int(len(palabra)); palabra2 = int; palabra3 = int; es_multiplo = int; result = int; a_string = palabra # Conversion de string a ASCII ASCII_values = [] for character in a_string: ASCII_values.append(ord(character)) # Resolucion de problemas palabra2 = (palabra1 % 5 == 0); result = ((+5) - palabra1); # Muestra en pantalla los resultados print('>---------------------------------------------------------<'); # Condicion para agregar 4 veces el numero que falta para llegar al multiplo if (result % 5 == 0): print('Cantidad de letras: ', palabra1); else: print('Cantidad de letras y mas las faltantes: ',palabra,result,result,result,result) print('>---------------------------------------------------------<'); print('Verificacion si es multiplo de 5: ',palabra2); print('>---------------------------------------------------------<'); print('Letras restantes para alcanzar el multiplo de 5: ',result); print('>---------------------------------------------------------<'); print('Valor de cada letra en ASCII: ',ASCII_values); print('>---------------------------------------------------------<');
false
fd8fbbc10b3cf4a4f960a7234229be4d2bd6aa17
MrBlackred/python
/section3.py
481
4.28125
4
# list ''' name = ['ame', 'nts', 'fb', 'XQ', 'y'] print(name) print(name[0].title()) print(name[-1]) # end element ## 3-2 append change del insert name[0] = 'kaka' #change name.append('hel') name.insert(0, 'lx') name2 = name.pop() name3 = name.pop(2) name.remove('kaka') del name[1] print(name) print(name2) print(name3) ''' ## sort cars = ['bmw', 'audi', 'tyt', 'sbr'] # cars.sort() #forver print(cars) # temporary print(sorted(cars)) print(cars) cars.reverse() print(cars)
false
889fe072686f7c2376300452cea08d619d326540
adomiter/CAAP-CS
/assignment_2/practice10.py
548
4.1875
4
#modify the above program def Easter(year): a = year%19 b = year%4 c = year%7 d = (19a + 24)%30 e = (2b+4c+6d+5)%7 exceptions = {"1954", "1981", "2049", "2079"} if year == exceptions; print("The date for Easter in", year,"is April", (22+d+e)-24, "," year) elif (22+d+e) > 31: print("The date for Easter in", year,"is April", (22+d+e)-31, "," year) def main(): year =int(input("What is the year?")) Easter(year) main()
false
2111d6fda9adc76a528dd5782c92931b486fba42
adomiter/CAAP-CS
/Practices_Ch8/quiz_2.py
327
4.15625
4
def word_length(sentence): sentence_array=sentence.split(" ") num_words=len(sentence_array) sum=0 for i in sentence_array: length_word=len(i) sum += length_word return(sum/num_words) def main(): user_sentence=input("What is the sentence?") print(word_length(user_sentence)) main()
true
c8a092a5ef6048a1b7de4b5b8bba925e807da787
A-fish-in-Lake-Baikal/python-exercise
/110Questions/58.py
237
4.125
4
# -*- coding: utf-8 -*- #使用pop和del删除字典中的”name”字段,dic={“name”:”zs”,”age”:18} dic1 = {"name":"zs","age":18} dic2 = {"name":"zs","age":18} dic1.pop("name") print(dic1) del dic2["name"] print(dic2)
false
074b5c41d84ebf7a30362101ae6a0c404840b70f
spoorthyvv/Python_workshop
/day2/p5.py
204
4.1875
4
import numpy as np List=[] num=int(input("Enter the number of elements")) print('Enter the elements: ') for i in range(num): List.append(int(input())) print('Average Of The Numbers Is: ',np.mean(List))
true
57bcf5cd33907e850f05e7f5f10c45c5020960ba
spoorthyvv/Python_workshop
/day1/offline_exercises_session1_day1/program5.py
480
4.1875
4
num1=int(input("Enter the first number: ")) num2=int(input("Enter the second number: ")) num3=int(input("Enter the Third number: ")) num4=int(input("Enter the fourth number")) def find_Biggest(): if(num1>=num2) and (num1>=num2): greatest=num1 elif(num2>=num1) and (num2>=num3): greatest=num2 elif(num3>=num4) and (num3>=num4): greatest=num3 else: greatest=num4 print("greatest number is",greatest) find_Biggest();
true
057f90b504c71f45eb2e766b9d663f5d767f20b8
santosh6171/pyScripts
/reverseSentence.py
246
4.375
4
def get_reverse_string(str): liststr = str.split() return " ".join(liststr[::-1]) string = input("Enter a sentence to be reversed\n") reverseString = get_reverse_string(string) print ("Reversed string is: {0}" .format(reverseString))
true
4295e7f056474a6453ef15da6d17a18ff890e5f1
surya1singh/Python-general-purpose-code
/multithreading/simple_use.py
2,024
4.1875
4
from threading import Thread, Lock, active_count, current_thread, Timer, enumerate import time def first_threads(): first = Thread(target=print, args=("This is print statement is with input :",1)) second = Thread(target=print, args=("This is print statement is with input :",2)) third = Thread(target=print, args=("This is print statement is with input :",3)) print(first.getName()) # prints name of the thread first.start() second.start() third.start() first_threads() # create three threads class myThread(Thread): def __init__(self): super(myThread, self).__init__() def run(self): print("Starting" , self.getName()) time.sleep(1) print("Exiting" , self.getName()) print("Threads are not synchronized") # Create new threads for i in range(6): threadX = myThread() threadX.start() print("active thread at this point :", active_count()) print(current_thread()) # main thread time.sleep(2) threadLock = Lock() class myThreadLock(Thread): def __init__(self): super(myThreadLock, self).__init__() def run(self): print("Starting" , self.getName()) threadLock.acquire() time.sleep(1) print(current_thread()) # child thread threadLock.release() print("Exiting" , self.getName()) print("\n\nThreads are not synchronized") # Create new threads for i in range(6): threadX = myThreadLock() threadX.start() print("Exiting Main Thread") time.sleep(1) # other methods # threading.enumerate() #This function returns a list of all active threads. It is easy to use. Let us write a script to put it in use: for thread in enumerate(): print("Thread name is %s." % thread.getName()) #threading.Timer() #This function of threading module is used to create a new Thread and letting it know that it should only start after a specified time. Once it starts, it should call the specified function. def delayed(): print("I am printed after 3 seconds!") thread = Timer(3, delayed) thread.start()
true
a9a263f4b3a58c22a57d5f06ba4b17d98707e0c4
Aperocky/leetcode_python
/007-ReverseInteger.py
945
4.21875
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ size = 1 if x < 0: size = -1 x = -x mystr = str(x) mystr = mystr[::-1] new = int(mystr) if new > 2**31 - 1: return 0 elif new < -2**31: return 0 else: return size * new def test(self): x = 2389375291 print(self.reverse(x)) soln = Solution() soln.test()
true
f481a25733269c39d82eb807e0c549550b19dfdf
nitzjain/practice
/array/create_own_dynamic_array.py
1,843
4.3125
4
''' the aim is to create your own dynamic array. If the array gets filled up, then double the size of the array. So we create a new array with double the size and rename it to the first array. We use ctypes library to create an array object. ''' import ctypes class DynamicArray(object): #init method. Has 3 components to initialize def __init__(self): self.n = 0 #element count self.capacity = 1 #array capacity self.A = self.make_array(self.capacity) #make array is a func we will create which will create an array with the given capacity. A is just a reference for array name. #length method to give the array's length def __len__(self): return self.n #retrieve an element from the array. If the index k is out of bounds, return error else return the value at k. def __getitem__(self, k): if not 0 <= k < self.n: return IndexError('K is out of bounds!!!!') return self.A[k] #add an element to the array. If the elements are more, double the size of the array. def append(self,element): if self.n == self.capacity: self._resize(2*self.capacity) self.A[self.n] = element self.n += 1 #user defined function to create a new array B, copy all elements of A to B and rename B to A. def _resize(self,new_cap): B = self.make_array(new_cap) for i in range(self.n): B[i] = self.A[i] self.A = B self.capacity = new_cap #using ctypes to make actual object. def make_array(self,new_cap): return (new_cap * ctypes.py_object)() #actual call D = DynamicArray() D.append(1444) print(D.__getitem__(0)) D.append(2000) print(D.__getitem__(1)) print(D.__len__()) #or C = DynamicArray() C.append(12) print(C[0]) C.append(20) print(C[1]) print(len(C))
true
4482f2a0cf59f804ae3a604d2a7ad2c7a1663347
ben-whitten/ICS3U-Unit-4-03-Python
/square_to_be_fair.py
2,257
4.21875
4
#!/usr/bin/env python3 # Created by: Ben Whitten # Created on: October 2019 # This is a program which tells you the total value of a number. # This allows me to do things with the text. class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def main(): # This is what runs the program. print("") print("This program will tell you the" " numbers which square into another number...") print('') while True: # Input number_as_string = input(color.BOLD + color.YELLOW + 'Input a positive' ' and whole number: ' + color.END) number_total = 0 next_full_number = 0 # This is the joe mama easter egg, its just for fun. if number_as_string == ("who's joe"): print("") print(color.BOLD + 'JOE MAMA!' + color.END) print(color.RED + 'Joe mama mode has now been enabled...' + color.END) # Process try: chosen_number = int(number_as_string) if chosen_number > 0: for next_full_number in range(chosen_number + 1): print("{0}^2 = {1}" .format(next_full_number, next_full_number**2)) number_total = number_total + next_full_number**2 print(color.GREEN + 'total = {0}'.format(number_total) + color.END) break else: print('') print(color.PURPLE + color.UNDERLINE + 'That is not a positive' ' and/or whole number...' + color.END) print("") print("") # This stops them from putting in something let bob and gets them to # re-input their age. except Exception: print('') print(color.PURPLE + color.UNDERLINE + 'That is not a positive' ' and/or whole number...' + color.END) print("") print("") if __name__ == "__main__": main()
true
ea76bb800fb75050700f066e2e4c7b0b68e879a4
Ramshiv7/Python-Codes
/Timer.py
302
4.28125
4
# Write a Python function which display timer(in Seconds) import time def timer(i): while i>0: print(i) time.sleep(1) i-= 1 try: i = int(input('Set the Timer for (Seconds): ')) int(i) timer(i) except ValueError: print('Input is not an INTEGER !')
true
d9d45ba89127f5703db72deae8b44add3ed03919
7minus2/Python
/Excercises/highest_even.py
404
4.46875
4
#!/usr/local/bin/python3 def highest_even(my_list): ''' Info: Get the highest even number from a list of numbers \n Example: highest_even([10,2,3,4,8,11]) # returns 10 ''' even_list = [num for num in my_list if num % 2 == 0] highest_number = sorted(even_list, reverse=True) return highest_number[0] if __name__ == "__main__": print(highest_even([10, 2, 3, 4, 8, 11]))
true
93fdf41bfe452b6a82d8683df202919f24bf802c
Lemito66/Python
/SobreCargaOperadores.py
1,029
4.21875
4
class Vector(object): def __init__ (self, x, y,z): self.x = x self.y = y self.z=z def __repr__ (self): return '(%f, %f,%f)' % (self.x, self.y,self.z) def __mul__ (self, v): #sobrecarga de multiplicacion return Vector (self.x *v.x, self.y *v.y, self.z*v.z) def productoEscalar(self): resultado= self.x+self.y+self.z return resultado def segundoTermino(self,A): return Vector (self.x *A, self.y *A, self.z*A) def __sub__ (self, v): #robrecarga resta return Vector (self.x - v.x, self.y - v.y,self.z-v.z) vectorIncidencia = Vector(1, 0,-1) vectoNormal = Vector(0, 0,1) # z = Vector(4,5,2) resultadoProductEs= (vectorIncidencia*vectoNormal) productoEscalar=Vector.productoEscalar(resultadoProductEs) #print(productoEscalar) A=productoEscalar*2 segundoTermino=Vector.segundoTermino(vectoNormal,A) formula=(vectorIncidencia-segundoTermino) print("El resultado es " ,formula) # print(productoEscalar)
false
9787c525e089d6aac97d7279a37b84ee7428ba88
Philstrae/001-projet
/san_antonio.py
1,431
4.15625
4
import random import json # -*- coding: utf8 -*- quotes= [ "Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !", "On doit pouvoir choisir entre s'écouter parler et se faire entendre." ] #characters = [ # "alvin et les Chipmunks", # "Babar", # "betty boop", # "calimero", # "casper", # "le chat potté", # "kirikou" #] def read_value_from_json(): values = [] with open('characters.json') as f: data = json.load(f) for entry in data: values.append(entry['character']) return values def get_random_item(my_list): rand_numb = random.randint(0,len(my_list) - 1) item = my_list[rand_numb] return item def random_character(): all_values = read_value_from_json() return get_random_item(all_values) def capitalize(words): for word in words: word.capitalize() def message(character, quote): capitalize(character) capitalize(quote) return "{} a dit : {}".format(character, quote) # Show random quoteinput() user_answer = input("Tapez entrée pour connaître une autre citation ou B pour quitter le programme.") while user_answer != "B": print(message(get_random_item(characters), random_character())) user_answer = input("Tapez entrée pour connaître une autre citation ou B pour quitter le programme.")
false
02bde541cb9fac492db28cc4d9cdec72918afeaf
pranali04/practice
/inheritance.py
1,112
4.25
4
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. #print("Hello world") class math: def __init__(self,a,b): print("math class") class divide(math): def __init__(self,a,b): self.a = a self.c = b print("divide initialized") #super().__init__(a,b) def divide(self): print(self.a/self.c) class mult(math): def __init__(self,a,b): #divide.__init__(self,b,c) print("mult function ini") #super().__init__(a,b) self.a = a self.b = b def divide(self): print("overrrrrr") #def divide(self,a,b): #print("from mult class") #print(a/b) def mult(self): print(self.a*1) class calc(mult,divide): def __init__(self,a,b): super().__init__(a,b) def printing(self): super().divide() #def common_int(obj): # obj.divide() A = calc(4,6) del A.a print(A.b) #B = mult(6,8) #common_int(A) #common_int(B) A.printing() #print(calc.__mro__) #A.divide() #A.divide(2,8) #A.mult()
false
d2bfc5e779a9a7f493f990ab092856dd6bbee7c8
danieljobvaladezelguera/CYPDANIELJVE
/for3.py
208
4.15625
4
for v in range(3,31,3): print("Hola",v) for v in range(20,-1,-1): print("Hola",v) print('------------------------') n = int(input("Dame un numero: ")) for x in range(0,n,1): print("+",end="")
false