blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
36d59d8a1a2efc18dba383797d90efbbf4bed1ee
thecoderarnav/C-98
/counting.py
340
4.28125
4
def countingwords(): fileName = input("ENTER FILE NAME") numberofcharacters = 0 file= open(fileName,"r") for line in file: data = file.read() #words = line.split() numberofcharacters = len(data) print ("Number of Characters") print(numberofcharacters) countingwords()
true
bcd2e33743c0415435f74f87b1c32ba9f3450e72
chyidl/leetcode
/0098-validate-binary-search-tree/validate-binary-search-tree.py
1,442
4.21875
4
# Given the root of a binary tree, determine if it is a valid binary search tree (BST). # # A valid BST is defined as follows: # # # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the left and right subtrees must also be binary search trees. # # #   # Example 1: # # # Input: root = [2,1,3] # Output: true # # # Example 2: # # # Input: root = [5,1,4,null,null,3,6] # Output: false # Explanation: The root node's value is 5 but its right child's value is 4. # # #   # Constraints: # # # The number of nodes in the tree is in the range [1, 104]. # -231 <= Node.val <= 231 - 1 # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: TreeNode) -> bool: # Solution: In-order 中序遍历 -- 升序 inorder = self.inorder(root) return inorder == list(sorted(set(inorder))) def inorder(self, root): if root is None: return [] # 左 根 右 return self.inorder(root.left) + [root.val] + self.inorder(root.right) # Solution: Recurision: 递归函数 # 左子树取最大值 max 右子树取最小值 min # 判断 max < root; root > min
true
e7df3aa457b5bdcfa8b0e8c35b431f31313c886e
septos/learnpython
/sets.py
705
4.21875
4
''' Sets 1.Unordered 2.Unindexed 3.newset = {orange,banana,fig} ''' new_fruits = {"lemon","fig","cherry"} print(new_fruits) print("-------------------------------------------------------------------------------") #for loop for x in new_fruits: print(x) print("-------------------------------------------------------------------------------") #add value new_fruits.add("orange") print(new_fruits) new_fruits.update(["mango","grape"]) print(new_fruits) print(len(new_fruits)) print("-------------------------------------------------------------------------------") #remove new_fruits.remove("fig") print(new_fruits) #remove = pop x = new_fruits.pop() print(x) new_fruits.clear() print(new_fruits)
true
e926d5b9a9f8e73cf5e0277853d7414fee12a5dc
navaneeth2324/256637_DailyCommits
/secondsmallest.py
245
4.1875
4
# Write a Python program to find the second smallest number in a list list=[] n=int(input("Size of list : ")) for i in range(0,n): item=int(input()) list.append(item) print("List : ",list) list.sort() print("Second Smallest :",list[1])
true
2c7f55a161747f33675e72d3d60d4464640521a2
Michal-Kok/WAR2021
/python tasks/chris.py
813
4.25
4
def name_in_str(sentence, name): return """ Simple as that, your task is to find name within given sentence, like in the example: Across the rivers. --- chris c h ri s Make it case sensitive. Letters must appear in the right order. """ assert name_in_str("Across the rivers", "chris") is True assert name_in_str("Next to a lake", "chris") is False assert name_in_str("Under a sea", "chris") is False assert name_in_str("A crew that boards the ship", "chris") is False assert name_in_str("A live son", "Allison") is False assert name_in_str("Just enough nice friends", "Jennifer") is False assert name_in_str("thomas", "Thomas") is True assert name_in_str("pippippi", "Pippi") is True assert name_in_str("pipipp", "Pippi") is False assert name_in_str("ppipip", "Pippi") is False print('noice')
true
cf37e6f4fd508e8ff33efd07e80e64fcf84af3ee
shaheryarshaikh1011/tcs_prep
/prime.py
565
4.125
4
lower = int(input("Enter Lower bound of the range")) upper = int(input("enter Upperbound of the range")) print("Prime numbers between", lower, "and", upper, "are:") #initialize variable to store sum of prime numbers sum=0; for num in range(lower + 1, upper ): # all prime numbers are greater than 1 if num == 1: break; else: for i in range(2, num): if (num % i) == 0: break else: print(num) sum=sum+num; print("Sum of prime numbers between ",lower," and ",upper," is ",sum)
true
a65b1ff98ba3df1b73a3c854fb04278ac804ff2f
chrishendrick/Python-Bible
/cinema.py
1,113
4.25
4
# cinema ticketing # working with dictionaries, while loops, if/elif/else # "name":[age,tickets] films = { "The Big Lebowski":[17,5], "Bourne Identity":[18,5], "Tarzan":[15,3], "Ghost Busters":[12,5] } while True: choice = input("Which film would you like to watch?: ").strip().title() if choice in films: #check number of tickets left num_seats = films[choice][1] if num_seats > 1: print("Great, there are {} seats left!".format(films[choice][1])) elif num_seats == 1: print("Great, there is {} seat left!".format(films[choice][1])) else: print("Sorry, we are sold out!") continue #moves to the next iteration in the while loop #check user age age = int(input("How old are you?: ").strip()) if age >= films[choice][0]: print("Enjoy the film!") films[choice][1] = films[choice][1] - 1 else: print("You're not old enough!") elif choice == "Exit": break else: print("We don't have that film...")
true
bf44413ec101466043c14961e255cd0dc1ab5af7
dimitrisgiannak/Python-Private_School-Part_B
/files/PV_methods2.py
1,081
4.1875
4
from datetime import date ''' For details check README ''' error_message3 = 'You must input an integer' def getdate(datetime_ , statement , empty): while True: date1 = 0 try: print_message = f'Please write the {datetime_} of the {statement} ' date = input(print_message + '\n') if not date: date1 = int(empty) break else: date1 = int(date) break except ValueError: print(error_message3.center(75) , '\n') return date1 #----------------------------------------------------------------------------------------------------------------------------------------------------------- def getmarks(value): while True: mark1 = 0 try: mark = input(value) if not mark: mark = -1 break else: mark1 = int(mark) break except ValueError: print(error_message3 , '\n') return mark1
true
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
4a7ba22c431cb61001dad9d7d1656e8bcc257b03
Sagar-1807/Python-Projects
/Algorithms/Selection Sort.py
500
4.28125
4
# MULTIPLE SWAPPING CONSUME MUCH CPU POWER,OR MEMORY POWER # SORT FROM START TO END def bubblesort(list): for i in range(5): # UPPER INDEX :7, INITIAL i=0 min=i for j in range(i, 6): if list[j] < list[min]: min = j temp = list[i] list[i] = list[min] list[min] = temp print(list) list=[12,18,27,36,11,10] bubblesort(list) print(" "),print("---Below is final sorted list ---- ") print(list)
true
f9649f0473bc7900d653fd0e216a35d95b6412a3
gxgarciat/Playground-GUI-Tkinter
/4_entry.py
738
4.375
4
from tkinter import * # Everything on tkinter is based using widgets # The program will expand depending on the content root = Tk() # For this, an entry widget will be required e = Entry(root,width=50,borderwidth=5) e.pack() # This will get the event from clicking the Button. It needs to be inside of the function # e.get() # This will insert a message in the entry box e.insert(0,"Enter your name: ") # Defining events that will occur when pressing the Button def myClick(): fetching = e.get() myLabel = Label(root,text="Hello " + fetching) myLabel.pack() # This will create a label widget myButton = Button(root,text="Your name is: ",command=myClick) myButton.pack() # This will keep it as a loop root.mainloop()
true
4236a00fc82ac2bed48764a68e3bb8f4be2791b5
webfudge95/codenation
/DayTwo/challenge6.py
444
4.3125
4
def is_even(num): if (num % 2) == 0: return True else: return False def addition(num1, num2): num3 = num1 + num2 return num3 num1 = int(input("What's the first number: ")) num2 = int(input("What's the second number: ")) num3 = addition(num1, num2) print("The sum of {} and {} is {}".format(num1, num2, num3)) if is_even(num3): print("And that number is even.") else: print("And that number is odd.")
true
ae6b39bf461f69f0dd0e01b562925c852693e15a
JPB-CHTR/mycode
/challenge_labs/sleepytime.py
975
4.1875
4
#!/usr/bin/env python3 def toddler(): diaper = input("Is the diaper wet? (Y or N)") if diaper == "Y": print("Change Diaper") elif diaper == "N": print("Give milk") else: print("You should have answered Y or N") def teen(): wakestate = input("Is the kid sleep walking (Y or N)") if wakestate == "Y": print("Walk back to bed") elif wakestate =="N": print("Ask why they decided it was a good idea to drink a monster?") else: print("You should have answered Y or N") while True: try: age = int(input("Please Enter your child's age: ")) break except ValueError: print("seriosly bro, maybe try a whole number") if age >=0 and age <= 4: print("I see you have a todler, god bless") toddler() elif age >= 5 and age <= 17: print("Well here you go") teen() elif age > 18: print("Child out of range. Move out") else: print("Try a positive number")
true
64d16b3172d910897e8f36d186684e9d88f46cb7
bundu10/lpthw
/example4.py
1,987
4.25
4
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print("USING THE NORMAL METHOD OF (CONCATENATE) STRINGS") # Blank line print() print("There are", cars, "cars available.") print("There are only", drivers, "drivers available.") print("There will be", cars_not_driven, "empty cars today.") print("We can transport", carpool_capacity, "people today.") print("We have", passengers, "to carpool today.") print("We need to put about", average_passengers_per_car, "in each cars.") print() print(">" * 50) print(">" * 50) print() # This code is simillar to the code above but the format is different. # USING THE (str) METHOD THE SAME CODE CAN BE WRITTEN IN THIS FORMAT. print("USING THE (str) method:") # Blank line print() print("There are " + str(cars) + " cars available.") print("There are only " + str(drivers) + " drivers available.") print("There will be " + str(cars_not_driven) + " empty cars today.") print("We can transport " + str(carpool_capacity) + " people today.") print("We have " + str(passengers) + " to carpool today.") print('We need to put about ' + str(average_passengers_per_car) + ' in each cars.') print() print(">" * 50) print(">" * 50) print() # This code is simillar to the code above but the format is different. # USING THE (.format) METHOD THE SAME CODE CAN ALSO BE WRITTEN IN THIS FORMAT. print("USING THE (.format) method:") # Blank line print() print("There are {} cars available.".format(cars)) print("There are only {} drivers available.".format(drivers)) print("There will be {} empty cars today.".format(cars_not_driven)) print("We can transport {} people today.".format(carpool_capacity)) print("We have {} to carpool today.".format(passengers)) print("We need to put about {} in each cars.".format(average_passengers_per_car))
true
0f75d6bf0c8928802e6e31076ba6d42bccc2ae14
HK002/JavaBasics
/Code/Data Structures/Linked Lists/MiddleElement.py
1,269
4.125
4
class Node: def __init__(self,data): self.value = data self.link = None class LinkedList: def __init__(self): self.start = None def insert(self,data): if self.start is None: self.start = Node(data) else: x = self.start while x.link is not None: x = x.link x.link = Node(data) def display(self): if self.start is None: print("List is Empty") else: x=self.start while x is not None: print(x.value, end = " ") x = x.link def middleElement(self): if self.start is None : print("Empty List") else: spointer = self.start fpointer = self.start while fpointer is not None and fpointer.link is not None: spointer = spointer.link fpointer = fpointer.link.link print("\nMiddle Element : " + str(spointer.value)) obj=LinkedList() obj.insert(1) obj.insert(2) obj.insert(3) obj.insert(4) obj.insert(5) obj.display() obj.middleElement() obj.insert(6) obj.display() obj.middleElement()
true
3468217eda250070effb82e9c49c2a4ceeee9724
Neil-C1119/CIS156-Projects
/3exercise12.py
1,102
4.25
4
#Print the table of quantities and discount percentages print("Here is the table of discounts: \n") print(" QUANTITY | DISCOUNT") print("------------------------") print(" 10-19 | 10%") print(" 20-49 | 20%") print(" 50-99 | 30%") print(" 100 or more | 40%") #Store the user's package amount in a variable and convert it to an integer package_amount = int(input("\n\nHow many packages will you purchase?: ")) #If the package amount is 10 or more but less than 20 if package_amount >= 10 and package_amount <= 19: print("You will get a 10% discount.") #If the package amount is 20 or more but less than 50 elif package_amount >= 20 and package_amount <= 49: print("You will get a 20% discount.") #If the package amount is 50 or more but less than 100 elif package_amount >= 50 and package_amount <= 99: print("You will get a 30% discount.") #If the package amount is 100 or more elif package_amount >= 100: print("You will get a 40% discount.") #If the package amount is 10 or less else: print("You will not get a discount.")
true
9bcbe5a5caa77120fe736a32f57e83b393a443e4
Neil-C1119/CIS156-Projects
/6exercise6n9.py
2,498
4.21875
4
#Start of try try: #This opens the file as the var numbers, then closes the file once finished running with open("numbers.txt", "r") as numbers: #Variable for each line of the file lines = numbers.readlines() #Variable for the amount of lines in the file line_amount = len(lines) #Variables for calculation and the final answer calculate = 0 iter = 0 final_number = 0 #If there are multiple lines if line_amount > 1: #For each line for line in lines: #The string is stripped of the newline character and converted into a floating point number = float(line.strip("\n")) #Add the number to the calculate variable calculate = calculate + number #Record the amount of iterations AKA how many numbers there are iter = iter + 1 #Calculate the final number final_number = calculate / iter #Print the final number rounded to 2 decimal places print("The average is", round(final_number, 2)) #If there is only one line elif line_amount == 1: #Reset to the beginning of the file since we already read it for the lines variable above numbers.seek(0) #Variable to hold the string on the only line line = numbers.readline() #Variable that holds a list of each number that is separated by spaces numbers = line.split() #For each number in the numbers list for number in numbers: #Add the number (converted to floating point) to the calculate variable calculate = calculate + float(number) #Record the amount of iterations AKA how many numbers there are iter = iter + 1 #Calculate the final number final_number = calculate / iter #Print the final number rounded to 2 decimal places print("The average is", round(final_number, 2)) #If there is an IOError during the try statement tell the user the file couldn't be found except IOError: print("File could not be found. . .") #If there is a ValueError during the try statement tell the user one or more of the values are not valid numbers except ValueError: print("One or more of the values are not valid numbers. . .")
true
969dd51c64bf4eeab6f4f8c19360b1e7b4d3825b
Neil-C1119/CIS156-Projects
/4exercise12.py
597
4.40625
4
#Factorial #Ask the user to input a number to calculate number = int(input("Which number would you like to find the factorial of? ")) #Defining the factorial function def factorialFunc(number): #Set the final_number variable to start at 1 final_number = 1 #For every number between 1 and the user's number, including the user's number... for each in range(1,number + 1): #Add final_number * each number to the final number final_number = final_number * each print("The factorial of", number, "is", final_number) factorialFunc(number)
true
758db104ef47bfb2cd00843ef90063c2bbb86199
sharonbrak/DI-Sharon
/Week_4/day_3/Exercises_XP_Gold.py
1,746
4.28125
4
# Exercise 1 fruits = input('What is/are your favorite fruits? ') print(fruits) type(fruits) mylist = fruits.split(' ') newfruit = input('Type another fruit: ') if newfruit in mylist: print('you chose one of your favorite fruits! Enjoy!') else: print('You chose a new fruit. I hope you enjoy it too!') if len(mylist) >=2: last = mylist[-1] mylist.append("and") mylist.append(last) Exercise 2 mypassword =input('Give me a password: ') # We check if it includes a digit ifdigit = [] for x in mypassword: if x.isdigit(): print('yes') ifdigit.append(x) else: print('no') print(ifdigit) #Another way to check if digit # any([char.isdigit() for char in password]) if mypassword.upper() != mypassword and mypassword.lower() != mypassword and len(ifdigit)>0 and '@' in mypassword or '#' in mypassword or '$' in mypassword and len(mypassword)>=6 and len(mypassword) <=12: print('Great!') else: print('OOOPS!') # Exercise 3 for x in range(3,31): if x%3 == 0: print(x) # Exercise 4 mylist = [1,2,3,4,5,6,7,8,9,10] insertindex = 4 item = 'here' ''' We want to insert in index 5 the word 'here' ''' mylist1 = mylist[0:int(insertindex)] mylist2 = mylist[int(insertindex):len(mylist)] mylist1.append(item) newlist = mylist1 + mylist2 print(newlist) # Exercise 5 # Exercise 6 Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700. for x in range(1500,2701): if x % 7 == 0 and x % 5 ==0: print(x) # Exercice 7 mystring = 'hdzio hzias hzau hzuszajjo' numspace = 0 for x in mystring: if x == " ": numspace +=1 print(numspace) # Exercice 8 mystring = 'hdzio hzias hzau hzuszajjo' len(mystring.split())
true
f41aa1be3a521b5004c0ed67f26137d03c57d2dd
alvas-education-foundation/K.Muthu-courses
/25 May 2020/qstn_complex.py
1,627
4.21875
4
""" Problem Statement: Take an input string parameter and determine if exactly 3 question marks exist between every pair of numbers that add up to 10. If so, return true, otherwise return false. Some examples test cases are below: "arrb6???4xxbl5???eee5" => true "acc?7??sss?3rr1??????5" => true "5??aaaaaaaaaaaaaaaaaaa?5?5" => false "9???1???9???1???9" => true "aa6?9" => false """ #importing numpy module import numpy as np #Function checks the sum of pair numbers #Also finds the frequency of element '?' in the list def check(n1 , n2 , li): n = 0 for l in li: if l == '?': n += 1 num = n1 + n2 if num == 10: buf.append(n) #This function finds the pair numbers (num1 , num2) #Also groups the elements between the pair of numbers def group(input_string , x): list = [] num1 = int(input_string[x]) num2 = 0 x += 1 while x < len(input_string): if input_string[x].isdigit(): num2 = int(input_string[x]) break else: list.append(input_string[x]) x += 1 check(num1 , num2 , list) if __name__ == '__main__': input_string = input("Enter the string : ") global buf buf = [] #Finding digits in the input string for i in range(len(input_string)): if input_string[i].isdigit(): group(input_string , i) #Comparing the conditions and printing final result val = np.unique(buf) if len(val) == 1 and val[0] == 3: print('True') else: print('False')
true
68b024412a8e0ff9e57797211031660e0118a94e
alvas-education-foundation/K.Muthu-courses
/19 May 2020/Function.py
266
4.21875
4
# Convert the temperature into Fahrenheit, given celsuis as inpit using function. #Function definition def temp(c): f=(c*9/5)+32 return f c=int(input("Enter the temperature in celsius : ")) #Function call f=temp(c) #Output print("Temperature in Fahrenheit : ",f)
true
9d49d0866bfb843c538298bb26585fd6f75851bb
venkateshwaracholan/Thinkpython
/chapter 8/eight_ten.py
212
4.21875
4
def is_palindrome_modified(word): """Returns true if the string is palindrome in a sinle check statement without involving loop""" return word==word[::-1] print is_palindrome_modified("madam")
true
3b82dcc452a6fe1f964f02bb2661f56d7efc0a57
venkateshwaracholan/Thinkpython
/chapter 9/nine_one.py
212
4.15625
4
"""reads all the words from the text file and prints the words which has more than 20 characters""" fin = open('words.txt') for line in fin: word = line.strip() if(len(word) >= 20): print word
true
e2fa6f5594de3d52b39cae5fa29867778f5c520a
morganjacklee/com404
/1-basics/3-decision/8-nestception/bot.py
1,294
4.40625
4
print("Where shall I look?") print("Choices are:") print("""- Bedroom - Bathroom - Labratory - Somewhere else""") location = str(input()) # Using if, else and elif statements if location == "Bedroom" : print("Where in the bedroom?") print("""- Under the bed - Somewhere else""") location_bedroom = str(input()) if location_bedroom == "Under the bed" : print("Found some socks but no battery.") elif location_bedroom == "Somewhere else" : print("Found some mess but no battery.") elif location == "Bathroom": print("Where in the bathroom?") print("""- In the Bathtub - Somewhere else""") location_bathroom = str(input()) if location_bathroom == "In the bathtub" : print("Found a rubber duck but no battery.") elif location_bathroom == "Somewhere else" : print("It's wet and there is no battery.") elif location == "Labratory": print("Where in the labratory?") print("""- On the table - Somewhere else""") location_labratory = str(input()) if location_labratory == "On the table" : print("Found the battery!") elif location_labratory == "Somewhere else" : print("Found some tools but no battery.") elif location == "Somewhere else": print("I don't know where that is but I will keep looking!") else: print("I'm not sure what you mean!")
true
16214125be23fce25190cbb1857d02b14105e11d
warriorwithin12/python-django-course
/course/WarGameProject/hand.py
1,045
4.25
4
class Hand: ''' This is the Hand class. Each player has a Hand, and can add or remove cards from that hand. There should be an add and remove card method here. ''' def __init__(self, cards): self.cards = cards def add_card(self, card): """ Add card to hand if not exists previously. """ if card not in self.cards: self.cards.append(card) else: print("Card already in hand! Nothing added.") def remove_card(self): """ Remove a card from hand if hand has cards left. """ if len(self.cards) > 0: return self.cards.pop() else: print("No cards left in hand! Nothing removed.") return None def __del__(self): """ Delete a hand, deleting it's cards. """ del self.cards # print("Deleted cards from Hand") def __str__(self): return "Hand: {}".format(str(self.cards)) def len(self): return len(self.cards)
true
3f7d5cc212695f3f9459c5dca44d05d5a318c61c
vyanphan/codingchallenges
/reverse_linked_list.py
1,270
4.21875
4
''' Reversing a singly linked list in-place. You should be able to do this in O(n) time. Do not put the items into an array, reverse the array, and put them back into the linked list. ''' ''' For testing purposes. ''' class LinkedNode(object): data = None next = None def __init__(self, data): self.data = data class LinkedList(object): head = None tail = None def add(self, node): if type(node) is LinkedNode: if self.tail == None: self.head = node self.tail = node elif type(self.tail) is LinkedNode: self.tail.next = node self.tail = node def print_nodes(self): curr = self.head ans = '' while curr != None: ans += str(curr.data) + ' -> ' curr = curr.next print(ans + 'None') ''' Reverses linked list in-place in O(n) time. ''' def reverse(ll): prev = ll.head if prev != None: curr = prev.next while curr != None: ll.head.next = curr.next curr.next = prev prev = curr curr = ll.head.next ll.head = prev def reverse_tester(n): ll = LinkedList() for i in range(1, n+1): ll.add(LinkedNode(i)) ll.print_nodes() reverse(ll) ll.print_nodes() print() reverse_tester(0) reverse_tester(1) reverse_tester(2) reverse_tester(7)
true
bc5a2f1f7114718e5cc4406e165f252bdde907be
Audarya07/99problems
/P33.py
344
4.1875
4
# Determine whether two positive integer numbers are coprime. def gcd(a, b) : if b == 0: return a return gcd(b, a%b) num1 = int(input("Enter first number : ")) num2 = int(input("Enter Second number : ")) if gcd(num1, num2) == 1: print("Given numbers ARE co-primes") else : print("Given numbers are NOT co-primes")
true
38b08a3205e61662c82c1fce1aa055514e2f926c
SeggevHaimovich/Python-projects
/Aestroids/asteroid.py
2,520
4.75
5
############################################################################### # FILE : asteroid.py # WRITER : ShirHadad Seggev Haimovich, seggev shirhdd # EXERCISE : intro2cs2 ex10 2021 # DESCRIPTION: the class: Asteroid ############################################################################### import math class Asteroid: """ A class for the asteroid object. the class builds an asteroid object with the following information: location, speed, size and radius. the asteroid object purpose is to save all the data of a single asteroid. """ INITIAL_SIZE_ASTEROID = 3 def __init__(self, location, speed, size=INITIAL_SIZE_ASTEROID): """ builds the asteroid object. gets the location and speed from the class call. sets the size variable as the initial value unless it gets size from the class call. calculates the radius variable according to the size. :param location: tuple (x and y coordinates) :param speed: tuple (speed in x direction and y direction) :param size: int """ self.__location = location self.__speed = speed self.__size = size self.__radius = self.__size * 10 - 5 def get_location(self): """ :return: the current location of the asteroid """ return self.__location def get_speed(self): """ :return: the current speed of the asteroid """ return self.__speed def get_size(self): """ :return: the size of the asteroid """ return self.__size def get_radius(self): """ :return: the radius of the asteroid """ return self.__radius def set_location(self, x, y): """ changes the location of the asteroid to the given coordinates. :param x: float :param y: float :return: None """ self.__location = (x, y) def has_intersection(self, obj): """ checks if the asteroid and the given object clash. :param obj: ship or torpedo :return:True if they clash and False otherwise """ distance = math.sqrt( (obj.get_location()[0] - self.__location[0]) ** 2 + ( obj.get_location()[1] - self.__location[1]) ** 2) if distance <= (self.get_radius() + obj.get_radius()): return True return False
true