blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
15e022eb2fbc2d17ee9dd7787a5c301d43dbb89a
GitLeeRepo/PythonNotes
/basics/sort_ex1.py
777
4.59375
5
#!/usr/bin/python3 # Examples of using the sorted() function # example function to be used as key by sorted function def sortbylen(x): return len(x) # List to sort, first alphabetically, then by length a = [ 'ccc', 'aaaa', 'd', 'bb'] # Orig list print(a) # Sorted ascending alphabetic print(sorted(a)) # sorted decending alphabetc print(sorted(a, reverse=True)) # use the len() function to sort by length print(sorted(a, key=len)) # use my own custom sort key function print(sorted(a, key=sortbylen)) # use my custom sort key function reversed print(sorted(a, key=sortbylen, reverse=True)) # Orig list still unchanged print(a) # but the sort() method will change the underlying list # unlike the sorted function call which creates a new one a.sort() print(a)
true
8da7f3ba63ae287850cb95fdaf6991da36855947
GitLeeRepo/PythonNotes
/basics/python_sandbox01.py
1,833
4.1875
4
#!/usr/bin/python3 # Just a sandbox app to explore different Python features and techniques for learning purposes import sys def hello(showPrompt=True): s = "Hello World!" print (s) #using slice syntax below print (s[:5]) #Hello print (s[6:-1]) #World print (s[1:8]) #ello wo print (s[1:-4]) #ello wo - same result indexing from right if len(sys.argv) > 1: print ("Command line args: " + str(sys.argv[1:])) #print the command line args if they exists if showPrompt: name = input ("Name?") print ("Hello " + name) print ("Hello", name) #both valid, 2nd adds its own space else: print ("Input not selected (pass True on hello() method call to display input prompt)") def listDemos(): list1 = [1, 2, 3] print(list1) list2 = [4, 5, 6] list3 = list1 + list2 #adds list2 to the end of list1 print(list3) list4 = list2 + list1 #adds list1 to the end of list2 print(list4) print("List pointer:") list1Pointer = list1 #they point to same location list1[0] = "1b" print(list1) print(list1Pointer) print("List copy") list1Copy = list1[:] #makes a copy, two different lists list1[0] = 1 print(list1) print(list1Copy) def menuChoices(): print ("Choose:") print ("1 - call hello (demo strings and argv command lines)") print ("2 - list demo") print ("d - display menu choices") print ("x - exit program") def main(): menuChoices() select = input("Selection: ") while select != "x": if select == "1": hello(False) #hello() without arg will use the default specified in parameter def elif select == "2": listDemos() elif select == "d": menuChoices() select = input("Selection: ") main()
true
66d407d714258a6aceea8e800a10ba5994af040a
ecastillob/project-euler
/101 - 150/112.py
1,846
4.40625
4
#!/usr/bin/env python # coding: utf-8 """ Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ # In[1]: def arriba(N): valor = -1 actual = -1 for n_str in str(N): actual = int(n_str) if actual < valor: return False valor = actual return True # In[2]: def abajo(N): valor = 10 actual = 10 for n_str in str(N): actual = int(n_str) if actual > valor: return False valor = actual return True # In[3]: def es_bouncy(N): return not (arriba(N) or abajo(N)) # In[4]: arriba(134468), abajo(66420), es_bouncy(155349) # In[5]: def contar_bouncies(RATIO_LIMITE): contador = 0 ratio = 0 i = 100 while (ratio != RATIO_LIMITE): if es_bouncy(i): contador += 1 ratio = contador / i i += 1 return [contador, i - 1, ratio] # In[6]: contar_bouncies(0.5) # [269, 538, 0.5] # In[7]: contar_bouncies(0.9) # [19602, 21780, 0.9] # In[8]: contar_bouncies(0.99) # [1571130, 1587000, 0.99]
true
3ef7c91a7f379e5b8f4f328c0e79a9238d6bce08
aaryanredkar/prog4everybody
/project 2.py
327
4.3125
4
first_name = input("Please enter your first name: ") last_name = input("Please enter your last name: ") full_name = first_name +" " +last_name print("Your first name is:" + first_name) print("Your last name is:" + last_name) print ("Your complete name is ", full_name) print("Your name is",len(full_name) ,"characters long")
true
6cd1676e716a609f138136b027cbe6655c7292a4
obrienadam/APS106
/week5/palindrome.py
1,178
4.21875
4
def is_palindrome(word): return word[::-1] == word if __name__ == '__main__': word = input('Enter a word: ') if is_palindrome(word): print('The word "{}" is a palindrome!'.format(word)) else: print('The word "{}" is not a palindrome.'.format(word)) phrase = input('What would you like to say?: ').lower() if phrase == 'hello': print('Hello to you too!') elif phrase == 'goodbye': print('Goodbye!') elif phrase == 'how are you doing today?': print('Fine, thank you!') else: print('I did not understand that phrase.') from random import randint num = randint(1, 10) guess = int(input('Guess a number between 1 and 10: ')) if 1 <= guess <= 10: if guess == num: print('Good guess!') else: print('Terrible guess. The number was {}'.format(num)) else: print(num, 'is not between 1 and 10...') from random import randint num = randint(1, 10) guess = int(input('Guess a number between 1 and 10: ')) if not 1 <= guess <= 10: print(num, 'is not between 1 and 10...') else: if guess == num: print('Good guess!') else: print('Terrible guess. The number was {}'.format(num))
true
e65ff801f6792b85f1878d3520b994f2e9dfa682
Ernestbengula/python
/kim/Task3.py
269
4.25
4
# Given a number , check if its pos,Neg,Zero num1 =float(input("Your Number")) #Control structures -Making decision #if, if else,elif if num1>0: print("positive") elif num1==0 : print("Zero") elif num1<0: print(" Negative") else: print("invalid")
true
4359dd4f67584016be61c50548e51c8117ee2bc7
xpbupt/leetcode
/Medium/Complex_Number_Multiplication.py
1,043
4.15625
4
''' Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example 2: Input: "1+-1i", "1+-1i" Output: "0+-2i" Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. ''' class Solution(object): def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ t_a = self.get_real_and_complex(a) t_b = self.get_real_and_complex(b) c = self.calculate(t_a, t_b) return c[0] + '+' + c[1] +'i' def get_real_and_complex(self, c): a = c.split('+')[0] b = c.split('+')[1].split('i')[0] return (int(a), int(b)) def calculate(self, a, b): return (str(a[0]*b[0] - a[1]*b[1]), str(a[0]*b[1] + a[1]*b[0]))
true
edace158002f255b7bbfd8d5708575912ab065d9
Varsha1230/python-programs
/ch4_list_and_tuples/ch4_lists_and_tuples.py
352
4.1875
4
#create a list using[]--------------------------- a=[1,2,4,56,6] #print the list using print() function----------- print(a) #Access using index using a[0], a[1], a[2] print(a[2]) #change the value of list using------------------------ a[0]=98 print(a) #we can also create a list with items of diff. data types c=[45, "Harry", False, 6.9] print(c)
true
c43b35b690a329f582683f9b406a66c826e5cabf
Varsha1230/python-programs
/ch3_strings/ch3_prob_01.py
435
4.3125
4
#display a user entered name followed by Good Afternoon using input() function-------------- greeting="Good Afternoon," a=input("enter a name to whom you want to wish:") print(greeting+a) # second way------------------------------------------------ name=input("enter your name:") print("Good Afternoon," +name) #----------------------------------------------------- name=input("enter your name:\n") print("Good Afternoon," +name)
true
5b3ef497693bc27e3d5fee58a9a77867b8f18811
Varsha1230/python-programs
/ch11_inheritance.py/ch11_1_inheritance.py
731
4.125
4
class Employee: #parent/base class company = "Google" def showDetails(self): print("this is an employee") class Programmer(Employee): #child/derived class language = "python" # company = "YouTube" def getLanguage(self): print("the language is {self.language}") def showDetails(self): #overwrite showDetails()-fn of class "Employee" print("this is an programmer") e = Employee() # object-creation e.showDetails() # fn-call by using object of class employee p = Programmer() # object-creation p.showDetails() # fn-call by using object of class programmer print(p.company) # using claas-employee's attribute by using the object of class programmer
true
c25ee297552465456ca50c12ce5df934c9d399bf
IsaacMarovitz/ComputerSciencePython
/MontyHall.py
2,224
4.28125
4
# Python Homework 11/01/20 # In the Monty Hall Problem it is benefical to switch your choice # This is because, if you switch, you have a rougly 2/3 chance of # Choosing a door, becuase you know for sure that one of the doors is # The wrong one, otherwise if you didnt switch you would still have the # same 1/3 chance you had when you made your inital guess # On my honour, I have neither given nor received unauthorised aid # Isaac Marovitz import random num_simulations = 5000 no_of_wins_no_switching = 0 no_of_wins_switching = 0 # Runs Monty Hall simulation def run_sim(switching): games_won = 0 for _ in range(num_simulations): # Declare an array of three doors each with a tuple as follows (Has the car, has been selected) doors = [(False, False), (False, False), (False, False)] # Get the guess of the user by choosing at random one of the doors guess = random.randint(0, 2) # Select a door at random to put the car behind door_with_car_index = random.randint(0, 2) # Change the tuple of that door to add the car doors[door_with_car_index] = (True, False) # Open the door the user didn't chose that doesn't have the car behind it for x in range(2): if x != door_with_car_index and x != guess: doors[x] = (False, True) # If switching, get the other door that hasn't been revealed at open it, otherwise check if # the current door is the correct one if switching: for x in range(2): if x != guess and doors[x][1] != True: games_won += 1 else: if guess == door_with_car_index: games_won += 1 return games_won # Run sim without switching for first run no_of_wins_no_switching = run_sim(False) # Run sim with switching for the next run no_of_wins_switching = run_sim(True) print(f"Ran {num_simulations} Simulations") print(f"Won games with switching: {no_of_wins_switching} ({round((no_of_wins_switching / num_simulations) * 100)}%)") print(f"Won games without switching: {no_of_wins_no_switching} ({round((no_of_wins_no_switching / num_simulations) * 100)}%)")
true
155a6195c974de35a6de43dffe7f1d2065d40787
IsaacMarovitz/ComputerSciencePython
/Conversation2.py
1,358
4.15625
4
# Python Homework 09/09/2020 # Inital grade 2/2 # Inital file Conversation.py # Modified version after inital submisions, with error handeling and datetime year # Importing the datetime module so that the value for the year later in the program isn't hardcoded import datetime def userAge(): global user_age user_age = int(input("How old are you? (Please only input numbers) ")) print("\nHey there!", end=" ") user_name = input("What's your name? ") print("Nice to meet you " + user_name) user_age_input_recieved = False while (user_age_input_recieved == False): try: userAge() user_age_input_recieved = True except ValueError: print("Invalid Input") user_age_input_recieved = False # I got this datetime solution from StackOverflow # https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu print("So, you were born in " + str((datetime.datetime.now().year-user_age)) + "!") user_colour = input("What's your favourite colour? ") if user_colour.lower() == "blue": print("Hey, my favourite is blue too!") else: print(user_colour.lower().capitalize() + "'s a pretty colour! But my favourite is blue") print("Goodbye!") input("Press ENTER to exit") # On my honor, I have neither given nor received unauthorized aid # Isaac Marovitz
true
774ce49dd157eca63ab05d74c0d542dd33b4f14a
Nyame-Wolf/snippets_solution
/codewars/Write a program that finds the summation of every number between 1 and num if no is 3 1 + 2.py
629
4.5
4
Summation Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer greater than 0. For example: summation(2) -> 3 1 + 2 summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 tests test.describe('Summation') test.it('Should return the correct total') test.assert_equals(summation(1), 1) test.assert_equals(summation(8), 36) others solution: def summation(num): return (1+num) * num / 2 or def summation(num): return sum(range(1,num+1)) or def summation(num): if num > 1: return num + summation(num - 1) return 1
true
62ef143a7d1a7dd420ad2f2f4b8a4ec9dda89f4f
DanielOram/simple-python-functions
/blueberry.py
2,627
4.625
5
#Author: Daniel Oram #Code club Manurewa intermediate #This line stores all the words typed from keyboard when you press enter myString = raw_input() #Lets print out myString so that we can see proof of our awesome typing skills! #Try typing myString between the brackets of print() below print() #With our string we want to make sure that the first letter of each word is a capital letter #Try editing myString by calling .title() at the end of myString below - This Will Capitalise Every Word In Our String myCapitalString = myString print("My Capitalised String looks like \"" + myCapitalString + "\"") #Now we want to reverse myString so that it looks backwards! #Try reversing myString by putting .join(reversed(myCapitalString)) after the empty string below - it will look like this -> ''.join(reversed(myCapitalString)) myBackwardsString = '' #Lets see how we did! print(myBackwardsString) #Whoa that looks weird! #Lets reverse our string back so that it looks like normal! #Can you do that just like we did before? myForwardString = '' #remember to use myBackwardsString instead of myCapitalString ! print("My backwards string = " + "\"" + myBackwardsString + "\"") #Ok phew! we should be back to normal #Lets try reverse our string again but this time we want to reverse the word order! NOT the letter order! #To do this we need to find a way to split our string up into the individual words #Try adding .split() to the end of myForwardString kind of like we did before myListOfWords = ["We", "want", "our", "String", "to", "look", "like", "this!"] #replace the [...] with something that looks like line 27! #Now lets reverse our List so that the words are in reverse order! myBackwardsListOfWords = reversed(["Replace","this", "list", "with", "the", "correct", "list"]) #put myListOfWords here #Before we can print it out we must convert our list of words back into a string! #Our string was split into several different strings and now we need to join them back together #HINT: we want to use the .join() function that we used earlier but this time we just want to put our list of words inside the brackets and # NOT reversed(myBackwardsListOfWords) inside of the brackets! myJoinedString = ''.join(["Replace", "me", "with", "the", "right", "list!"]) # replace the [...] with the right variable! print(myJoinedString) #Hmmm our list is now in reverse.. but it's hard to read! #Go back and fix our issue by adding a space between the '' above. That will add a space character between every word in our list when it joins it together! #Nice job! You've finished blueberry.py
true
15cc2f889516a57be1129b8cad373084222f2c30
viniciuschiele/solvedit
/strings/is_permutation.py
719
4.125
4
""" Explanation: Permutation is all possible arrangements of a set of things, where the order is important. Question: Given two strings, write a method to decide if one is a permutation of the other. """ from unittest import TestCase def is_permutation(s1, s2): if not s1 or not s2: return False if len(s1) != len(s2): return False return sorted(s1) == sorted(s2) class Test(TestCase): def test_valid_permutation(self): self.assertTrue(is_permutation('abc', 'cab')) self.assertTrue(is_permutation('159', '915')) def test_invalid_permutation(self): self.assertFalse(is_permutation('abc', 'def')) self.assertFalse(is_permutation('123', '124'))
true
9332ac35cb63d27f65404bb86dfc6370c919c2be
viniciuschiele/solvedit
/strings/is_permutation_of_palindrome.py
1,117
4.125
4
""" Explanation: Permutation is all possible arrangements of a set of things, where the order is important. Palindrome is a word or phrase that is the same forwards and backwards. A string to be a permutation of palindrome, each char must have an even count and at most one char can have an odd count. Question: Given a string, write a function to check if it is a permutation of a palindrome. """ from unittest import TestCase def is_permutation_of_palindrome(s): counter = [0] * 256 count_odd = 0 for c in s: char_code = ord(c) counter[char_code] += 1 if counter[char_code] % 2 == 1: count_odd += 1 else: count_odd -= 1 return count_odd <= 1 class Test(TestCase): def test_valid_permutation_of_palindrome(self): self.assertTrue(is_permutation_of_palindrome('pali pali')) self.assertTrue(is_permutation_of_palindrome('abc111cba')) def test_non_permutation_of_palindrome(self): self.assertFalse(is_permutation_of_palindrome('pali')) self.assertFalse(is_permutation_of_palindrome('abc1112cba'))
true
7de1ba91ebbb95ade3f54e652560b2c65369b1e3
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s8_center_method.py
720
4.25
4
# The one-parameter variant of the center() method makes a copy of the original string, # trying to center it inside a field of a specified width. # The centering is actually done by adding some spaces before and after the string. # Demonstrating the center() method print('[' + 'alpha'.center(10) + ']') print('[' + 'Beta'.center(2) + ']') print('[' + 'Beta'.center(4) + ']') print('[' + 'Beta'.center(6) + ']') # The two-parameter variant of center() makes use of the character from the second argument, # instead of a space. Analyze the example below: print('[' + 'gamma'.center(20, '*') + ']') s1 = "Pasquale".center(30) print(s1) print("length:", len(s1)) s2 = "Pasquale Silvestre".center(50, "-") print(s2) print(len(s2))
true
27598f79de97818823527e23f3969c27959f8702
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s15_split.py
617
4.46875
4
# The # split() # method does what it says - it splits the string and builds a list of all detected substrings. # The method assumes that the substrings are delimited by whitespaces - the spaces don't take part in the operation, # and aren't copied into the resulting list. # If the string is empty, the resulting list is empty too. # Demonstrating the split() method print("phi chi\npsi".split()) # Note: the reverse operation can be performed by the join() method. print("-------------------------") # Demonstrating the startswith() method print("omega".startswith("meg")) print("omega".startswith("om"))
true
0c10af8575d97394bbcb9c2363a82fe424df2bd0
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/integers_octal_exadecimal.py
1,053
4.53125
5
# If an integer number is preceded by an 0O or 0o prefix (zero-o), # it will be treated as an octal value. This means that the number must contain digits taken from the [0..7] range only. # 0o123 is an octal number with a (decimal) value equal to 83. print(0o123) # The second convention allows us to use hexadecimal numbers. # Such numbers should be preceded by the prefix 0x or 0X (zero-x). # 0x123 is a hexadecimal number with a (decimal) value equal to 291. The print() function can manage these values too. print(0x123) print(4 == 4.0) print(.4) print(4.) # On the other hand, it's not only points that make a float. You can also use the letter e. # When you want to use any numbers that are very large or very small, you can use scientific notation. print(3e8) print(3E8) # The letter E (you can also use the lower-case letter e - it comes from the word exponent) # is a concise record of the phrase times ten to the power of. print("----------------------------------------------------------") print(0.0000000000000000000001) print(1e-22)
true
fd80e5cecb0c723cf52c16e6b112648476b37388
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Nested_Functions/NestedFunc1.py
548
4.1875
4
# Define three_shouts def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2), inner(word3)) # Call three_shouts() and print print(three_shouts('a', 'b', 'c')) print() tupla_prova = three_shouts('Pasquale', 'Ignazio', 'Laura') print(tupla_prova) var1, var2, var3 = tupla_prova print(var1, var2, var3)
true
15d42320cb2c5217991e7b6202330c9e5e5fa414
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s7.py
458
4.4375
4
# Demonstrating the capitalize() method print('aBcD'.capitalize()) print("----------------------") # The endswith() method checks if the given string ends with the specified argument and returns True or False, # depending on the check result. # Demonstrating the endswith() method if "epsilon".endswith("on"): print("yes") else: print("no") t = "zeta" print(t.endswith("a")) print(t.endswith("A")) print(t.endswith("et")) print(t.endswith("eta"))
true
a959f8c5d7ec65d50fea6f6ca640524a04e13501
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Regular_Expressions_in_Python/Positional_String_formatting/Positional_formatting1.py
812
4.15625
4
# positional formatting ------> .format() wikipedia_article = 'In computer science, artificial intelligence (AI), sometimes called machine intelligence, ' \ 'is intelligence demonstrated by machines, ' \ 'in contrast to the natural intelligence displayed by humans and animals.' my_list = [] # Assign the substrings to the variables first_pos = wikipedia_article[3:19].lower() second_pos = wikipedia_article[21:44].lower() # Define string with placeholders my_list.append("The tool '{}' is used in '{}'") # Define string with rearranged placeholders my_list.append("The tool '{1}' is used in '{0}'") # That's why it's called 'POSITIONAL FORMATTING' # Use format to print strings for my_string in my_list: print(my_string.format(first_pos, second_pos))
true
968bee9c854610fd5799d875dae04d4227c74cfe
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Functions and packages/PackagesInPython/MathPackageInPython.py
653
4.34375
4
""" As a data scientist, some notions of geometry never hurt. Let's refresh some of the basics. For a fancy clustering algorithm, you want to find the circumference, C, and area, A, of a circle. When the radius of the circle is r, you can calculate C and A as: C=2πr A=πr**2 To use the constant pi, you'll need the math package. """ # Import the math package import math # Definition of radius r = 0.43 # Calculate C C = 2*r*math.pi # Calculate A A = math.pi*r**2 # Build printout print("Circumference: " + str(C)) print("Area: " + str(A)) print() print(math.pi) print("PiGreco dal package math = " + str(math.pi))
true
100d7f48a899c20b52ee5479eccd7422a87aa667
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Lists/Python_Lists11.py
707
4.125
4
# you can also remove elements from your list. You can do this with the del statement: # Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change! x = ["a", "b", "c", "d"] print(x) del(x[1]) # del statement print(x) areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50, "poolhouse", 24.5, "garage", 15.45] print(areas) del(areas[-4:-2]) print(areas) """ The ; sign is used to place commands on the same line. The following two code chunks are equivalent: # Same line command1; command2 # Separate lines command1 command2 """
true
1ff840fef8bc267fcf37268800d9bd29dd86f521
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part2/Generators_and_GENfunc_yield/GEN2.py
462
4.34375
4
# [ LIST COMPREHENSION ] # ( GENERATOR ) # Recall that generator expressions basically have the same syntax as list comprehensions, # except that it uses parentheses () instead of brackets [] # Create generator object: result result = (num for num in range(31)) # Print the first 5 values print(next(result)) print(next(result)) print(next(result)) print(next(result)) print(next(result)) # Print the rest of the values for value in result: print(value)
true
6ab7b8b1135b74d6572efd98bb64f86f85e468ce
ryanmp/project_euler
/p076.py
1,263
4.15625
4
''' counting sums explanation via example: n == 5: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 if sum == 5 -> there are 6 different combos ''' def main(): return 0 # how many different ways can a given number be written as a sum? # note: combinations, not permutations def count_sum_reps(n): ''' my gut tells me that this can be formulated as a math problem... let's first see if we can detect the pattern: 1 -> 1 2 -> 1 3 -> 1+2, 1+1+1: 2 4 -> 1+3, 2+2,2+1+1, 1+1+1+1: 4 5 -> 6 6 -> 5+1, 4+2, 4+1+1, 3+3, 3+2+1, 3+1+1+1, 2+2+2, 2+2+1+1, 2+1+1+1+1, 1+1+1+1+1+1 : 10 7 -> 6+1 5+2 5+1+1 4+3 4+2+1 4+1+1+1 3+3+1 3+2+2 3+2+1+1 3+1+1+1+1 2+2+2+1 2+2+1+1+1 2+1+1+1+1+1 (7x)+1 : 14 8 -> 7+1 6+2 6+1+1 5 = "3" 4 = "4" 3+3+2 3+3+1+1 3+2+2+1 3+2+1+1+1 3+(5x)+1 "5" 2+2+2+2 ... "4" "1" : 19 9 -> yikes, I'm seeing the emergence of a pattern, n-1 rows. growing by +1 descending.. until it reaches the corner, but i would need to do several more in order to see the pattern on the bottom rows (after the corner), assuming there is a pattern ''' return 'not finished yet' if __name__ == '__main__': import boilerplate, time boilerplate.all(time.time(),main())
true
240066b054c327e6a05ab214ce54466ba9b39d6f
gonzrubio/HackerRank-
/InterviewPracticeKit/Dictionaries_and_Hashmaps/Sherlock_and_Anagrams.py
992
4.15625
4
"""Given a string s, find the number of pairs of substrings of s that are anagrams of each other. 1<=q<=10 - Number of queries to analyze. 2<=|s|<=100 - Length of string. s in ascii[a-z] """ def sherlockAndAnagrams(s): """Return the number (int) of anagramatic pairs. s (list) - input string """ n = len(s) anagrams = dict() for start in range(n): for end in range(start,n): substring = ''.join(sorted(s[start:end+1])) anagrams[substring] = anagrams.get(substring,0) + 1 count = 0 for substring in anagrams: freq = anagrams[substring] count += freq*(freq-1) // 2 return count def main(): #tests = ['abba','abcd','ifailuhkqq','kkkk'] #for test in tests: # 1<=q<=10 for _ in range(int(input())): # 1<=q<=10 print(sherlockAndAnagrams(input())) # 2<=|s|<=100 if __name__ == '__main__': main()
true
d1d844be30625c6e2038e0596b19c05cf9a489fa
DarioBernardo/hackerrank_exercises
/recursion/num_decodings.py
2,241
4.28125
4
""" HARD https://leetcode.com/problems/decode-ways/submissions/ A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The answer is guaranteed to fit in a 32-bit integer. Example 1: Input: s = "12" Output: 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). Example 2: Input: s = "226" Output: 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). Example 3: Input: s = "0" Output: 0 Explanation: There is no character that is mapped to a number starting with 0. The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0. Hence, there are no valid ways to decode this since all digits need to be mapped. Example 4: Input: s = "06" Output: 0 Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). """ from functools import lru_cache def num_decodings(s: str): @lru_cache(maxsize=None) # This automatically implement memoisation def recursive(s: str, index=0): if index == len(s): return 1 # If the string starts with a zero, it can't be decoded if s[index] == '0': return 0 if index == len(s) - 1: return 1 answer = recursive(s, index + 1) if int(s[index: index + 2]) <= 26: answer += recursive(s, index + 2) return answer return recursive(s, 0) din = [ "234", "2101", "1201234" ] dout = [ 2, 1, 3 ] for data_in, expected_result in zip(din, dout): actual_result = num_decodings(data_in) print(f"Expected: {expected_result} Actual: {actual_result}") assert expected_result == actual_result
true
5d792080e230b43aa25835367606510d0bb63af7
feynmanliang/Monte-Carlo-Pi
/MonteCarloPi.py
1,197
4.21875
4
# MonteCarloPi.py # November 15, 2011 # By: Feynman Liang <feynman.liang@gmail.com> from random import random def main(): printIntro() n = getInput() pi = simulate(n) printResults(pi, n) def printIntro(): print "This program will use Monte Carlo techniques to generate an" print "experimental value for Pi. A circle of radius 1 will be" print "inscribed in a square with side length 2. Random points" print "will be selected. Since Pi is the constant of proportionality" print "between a square and its inscribed circle, Pi should be" print "equal to 2*2*(points inside circle/points total)" def getInput(): n = input("Enter number of trials: ") return n def simulate(n): hit = 0 for i in range(n): result = simulateOne() if result == 1: hit = hit + 1 pi = 4 * float(hit) / n return pi def simulateOne(): x = genCoord() y = genCoord() distance = x*x + y*y if distance <= 1: return 1 else: return 0 def genCoord(): coord = 2*random()-1 return coord def printResults(pi, n): print "After", n, "simulations, pi was calculated to be: ", pi if __name__ == "__main__": main()
true
9e7d64fbc8fd69a5d56e3f65a057a2a3ce08da27
revanth465/Algorithms
/Searching Algorithms.py
1,403
4.21875
4
# Linear Search | Time Complexity : O(n) import random def linearSearch(numbers, find): for i in numbers: if(i==find): return "Found" return "Not Found" numbers = [1,3,5,23,5,23,34,5,63] find = 23 print(linearSearch(numbers,find)) # Insertion Sort | Time Complexity : O(N^2) def insertionSort(numbers): i = 2 while(i <= len(numbers)): j = i-1 while( j > 0 ): if(numbers[j] < numbers[j-1]): temp = numbers[j-1] numbers[j-1] = numbers[j] numbers[j] = temp j -= 1 else: break i += 1 return numbers # Binary Search | Time Complexity : O(logN) | With Insertion Sort : O(N^2) def binarySearch(): # Let's build a list of random numbers and a random value to find in the list. numbers = [random.randint(1,21) for i in range(10)] find = random.randint(1,21) numbers = insertionSort(numbers) low = 0 high = len(numbers) -1 while(low <= high): middle = (low + high) /2 if(numbers[middle] == find): return "Number Found" elif(find < numbers[middle]): high = middle - 1 else: low = middle + 1 return "Number Not Found" print(binarySearch())
true
6c82627929fa81cdd0998309ec049b8ef4d7bc86
Helen-Sk-2020/JtBr_Arithmetic_Exam_Application
/Arithmetic Exam Application/task/arithmetic.py
2,032
4.125
4
import random import math def check_input(): while True: print('''Which level do you want? Enter a number: 1 - simple operations with numbers 2-9 2 - integral squares of 11-29''') x = int(input()) if x == 1 or x == 2: return x break else: print('Incorrect format.') def check_answer(answer): while True: x = input() if x.strip('-').isdigit(): if int(x) == answer: print('Right!') return 'Right!' else: print('Wrong!') break else: print('Incorrect format.') def simple_operations(): total = 0 a = random.randint(2, 9) b = random.randint(2, 9) operator = random.choice('+-*') print(f"{a} {operator} {b}") if operator == "+": total = int(a) + int(b) elif operator == "-": total = int(a) - int(b) elif operator == "*": total = int(a) * int(b) return total def integral_squares(): num = random.randint(11, 29) print(num) square = math.pow(num, 2) return square def save_result(level, n): print("What is your name?") name = input() if level == 1: level_description = 'simple operations with numbers 2-9' elif level == 2: level_description = 'integral squares of 11-29' results = open('results.txt', 'a', encoding='utf-8') results.write(f'{name}: {n}/5 in level {level} ({level_description})') results.close() print('The results are saved in "results.txt".') level = check_input() counter = n = 0 while counter < 5: if level == 1: result = simple_operations() elif level == 2: result = integral_squares() if check_answer(result) == 'Right!': n += 1 counter += 1 print(f"Your mark is {n}/5. Would you like to save the result?") user_answer = str(input()) if user_answer.lower() == 'yes' or user_answer == 'y': save_result(level, n)
true
0a6b38b73eea3f054edadbf5dc5f08ee4c524cb1
Jrjh27CS/Python-Samples
/practice-python-web/fibonacci.py
690
4.21875
4
#Challenge given by https://www.practicepython.org #Jordan Jones Apr 16, 2019 #Challenge: Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. def fib(x): z = [] if x == 0: return z z.append(0) if x == 1: return z z.append(1) if x == 2: return z while len(z) != x: z.append(z[len(z)-1] + z[len(z)-2]) return z num = int(input("How many fibonacci numbers would you like starting from 0? Num:")) print(fib(num))
true
dcbe36488dc453401fb81abd4a01dd2fe29bcbbf
moribello/engine5_honor_roll
/tools/split_names.py
1,231
4.375
4
# Python script to split full names into "Last Name", "First Name" format #Note: this script will take a .csv file from the argument and create a new one with "_split" appended to the filename. The original file should have a single column labled "Full Name" import pandas as pd import sys def import_list(): while True: try: listname1 = sys.argv[1] list1 = pd.read_csv(listname1) break except: print(listname1) print("That doesn't appear to be a valid file. Please try again.") break return list1, listname1 def split_fullnames(df, listname): # new data frame with split value columns new = df["Full Name"].str.split(" ", n = 1, expand = True) # making separate first and last name columns from new data frame df["First Name"]= new[1] df["Last Name"]= new[0] df = df.drop(columns=['Full Name']) new_filename = listname[:-4] df.to_csv(new_filename+"_split.csv", index=False) print("Spaces removed. Changes written to file {}_split.csv.".format(new_filename)) def main(): list1, listname1 = import_list() split_fullnames(list1, listname1) if __name__ == "__main__": main()
true
86773d8aa5d642f444192ecc1336560c86d718ca
siddu1998/sem6_labs
/Cloud Computing/Assignment 1/question9.py
218
4.40625
4
# Write a Python program to find whether a given number (accept from the user) # is even or odd, print out an appropriate message to the user. n=int(input("please enter the number")) print("even" if n%2==0 else "odd")
true
316aa2bdc7e255944d154ce075592a157274c9bc
Jeremyreiner/DI_Bootcamp
/week5/Day3/daily_challenges/daily_challenge.py
2,874
4.28125
4
# Instructions : # The goal is to create a class that represents a simple circle. # A Circle can be defined by either specifying the radius or the diameter. # The user can query the circle for either its radius or diameter. # Other abilities of a Circle instance: # Compute the circle’s area # Print the circle and get something nice # Be able to add two circles together # Be able to compare two circles to see which is bigger # Be able to compare two circles and see if there are equal # Be able to put them in a list and sort them # ---------------------------------------------------------------- import math class Circle: def __init__(self, radius, ): self.radius = radius self.list = [] def area(self): return self.radius ** 2 * math.pi def perimeter(self): return 2*self.radius*math.pi def __le__(self, other): if self.radius <= other.radius: return True else: return False def __add__(self, other): if self.radius + other.radius: return self.radius + other.radius def add_circle(self): for item in self.list: if item not in self.list: self.list.append(item) def print_circle(self): return print(self.list) circle = Circle(50) circle_2 = Circle(7) print(circle.area()) Circle.add_circle(circle) Circle.add_circle(circle_2) print(Circle.print_circle(circle)) print(circle.perimeter()) print(circle.__le__(circle_2)) print(circle.__add__(circle_2)) # bigger_circle = n_circle.area + n_circle_2.area # print(bigger_circle.area()) # !class Racecar(): # def __init__(self, model, reg_no, top_speed=0, nitros=False): # self.model = model # self.reg_no = reg_no # self.top_speed = top_speed # self.nitros = nitros # if self.nitros: # self.top_speed += 50 # def __str__(self): # return self.model.capitalize() # def __repr__(self): # return f"This is a Racecar with registration: {self.reg_no}" # def __call__(self): # print(f"Vroom Vroom. The {self.model} Engines Started") # def __gt__(self, other): # if self.top_speed > other.top_speed: # return True # else: # return False # def drive(self, km): # print(f"You drove the {self.model} {km} km in {km / self.top_speed} hours.") # def race(self, other_car): # if self > other_car: # print(f"I am the winner") # else: # print(f"The {other_car.model} is the winner") # class PrintList(): # def __init__(self, my_list): # self.mylist = my_list # def __repr__(self): # return str(self.mylist) # car1 = Racecar("honda", "hello", 75, True) # car2 = Racecar("civic", "bingo", 55, True) # print(car1.__gt__(car2))
true
0cdc78355fca028bb19c771c343ae845b702f555
Jeremyreiner/DI_Bootcamp
/week5/Day1/Daily_challenge/daily_challenge.py
2,265
4.40625
4
# Instructions : Old MacDonald’s Farm # Take a look at the following code and output! # File: market.py # Create the code that is needed to recreate the code provided above. Below are a few questions to assist you with your code: # 1. Create a class called Farm. How should this be implemented? # 2. Does the Farm class need an __init__ method? If so, what parameters should it take? # 3. How many methods does the Farm class need? # 4. Do you notice anything interesting about the way we are calling the add_animal method? What parameters should this function have? How many…? # 5. Test your code and make sure you get the same results as the example above. # 6. Bonus: nicely line the text in columns as seen in the example above. Use string formatting. class Farm(): def __init__(self, name): self.name = name self.animals = [] self.sorted_animals = [] def add_animal(self, animal, amount = ""): if animal not in self.animals: added_animal = f"{animal} : {str(amount)}" self.animals.append(added_animal) def show_animals(self): # for animal in self.animals: print(f"These animals are currently in {self.name}'s farm: {self.animals}") # Expand The Farm # Add a method called get_animal_types to the Farm class. # This method should return a sorted list of all the animal types (names) in the farm. # With the example above, the list should be: ['cow', 'goat', 'sheep']. def get_animal_types(self): if __name__ == '__main__': sorted_by_name = sorted(self.animals, key=lambda x: x.animals) print(sorted_by_name) # Add another method to the Farm class called get_short_info. # This method should return the following string: “McDonald’s farm has cows, goats and sheep.”. # The method should call the get_animal_types function to get a list of the animals. macdonald = Farm("McDonald") macdonald.add_animal('cow', 5) macdonald.add_animal('sheep') macdonald.add_animal('sheep') macdonald.add_animal('goat', 12) macdonald.show_animals() all_animals = macdonald.animals macdonald.get_animal_types() # print(macdonald.get_info()) # McDonald's farm # cow : 5 # sheep : 2 # goat : 12 # E-I-E-I-0!
true
44971d0672295eea12f2d5f3ad8dad4faea2c47f
Bawya1098/python-Beginner
/Day3/Day3_Assignments/hypen_separated_sequence.py
273
4.15625
4
word = str(input("words to be separated by hypen:")) separated_word = word.split('-') sorted_separated_word = ('-'.join(sorted(separated_word))) print("word is: ", word) print("separated_word is:", separated_word) print("sorted_separated_word is: ", sorted_separated_word)
true
3da597b2bcdcdaf16bfa50bc86a060fa56173667
ND13/zelle_python
/chapter_2/futval.py
792
4.15625
4
#!/usr/bin/python3.6 # File: futval.py # A program that computes an investment carried 10 years into future # 2.8 Exercises: 5, 9 def main(): print("This program calculates the future value of a 10-year investment.") principal = float(input("Enter the principal amount: ")) apr = float(input("Enter the annualized interest rate: ")) length = int(input("Enter the length in years of investment: ")) inflation = float(input("Enter yearly rate of inflation: ")) apr = apr * .01 inflation = inflation * .01 for i in range(length): principal = principal * (1 + apr) principal = principal / (1 + inflation) year = i + 1 print(f"Year {year}: {principal:.2f}") print(f"The amount in {length} years is: {principal:.2f}") main()
true
7482b65b788259f74c8719944618f9d856417780
ND13/zelle_python
/chapter_3/pizza.py
450
4.3125
4
# sphere_2.py # calculates the price per square inch of circular pizza using price and diameter def main(): price = float(input("Enter the price for your pizza: $")) diameter = float(input("Enter the diameter of the pizza: ")) radius = diameter / 2 area = 3.14159 * radius ** 2 price_per_sq_inch = price / area print(f"The price per square inch of pizza is ${price_per_sq_inch:.2f}") if __name__ == '__main__': main()
true
def2e855860ded62733aa2ddcfe4b51029a8edd2
PSReyat/Python-Practice
/car_game.py
784
4.125
4
print("Available commands:\n1) help\n2) start\n3) stop\n4) quit\n") command = input(">").lower() started = False while command != "quit": if command == "help": print("start - to start the car\nstop - to stop the car\nquit - to exit the program\n") elif command == "start": if started: print("Car has already started.\n") else: started = True print("Car has started.\n") elif command == "stop": if started: started = False print("Car has stopped.\n") else: print("Car has already stopped.\n") else: print("Input not recognised. Please enter 'help' for list of valid inputs.\n") command = input(">").lower() print("You have quit the program.")
true
f6b50fb2c608e9990ed1e3870fd73e2039e17b3d
ananyo141/Python3
/uptoHundred.py
301
4.3125
4
#WAP to print any given no(less than 100) to 100 def uptoHundred(num): '''(num)-->NoneType Print from the given number upto 100. The given num should be less than equal to 100. >>>uptoHundred(99) >>>uptoHundred(1) ''' while(num<=100): print(num) num+=1
true
437c321c8a52c3ae13db3bfa5e48c7a5dac2c1eb
ananyo141/Python3
/gradeDistribution/functions.py
2,519
4.15625
4
# This function reads an opened file and returns a list of grades(float). def findGrades(grades_file): '''(file opened for reading)-->list of float Return a list of grades from the grades_file according to the format. ''' # Skip over the header. lines=grades_file.readline() grades_list=[] while lines!='\n': lines=grades_file.readline() lines=grades_file.readline() while lines!='': # No need to .rstrip('\n') newline as float conversion removes it automatically. grade=float(lines[lines.rfind(' ')+1:]) grades_list.append(grade) lines=grades_file.readline() return grades_list # This function takes the list of grades and returns the distribution of students in that range. def gradesDistribution(grades_list): '''(list of float)-->list of int Return a list of ints where each index indicates how many grades are in these ranges: 0-9: 0 10-19: 1 20-29: 2 : 90-99: 9 100 : 10 ''' ranges=[0]*11 for grade in grades_list: which_index=int(grade//10) ranges[which_index]+=1 return ranges # This function writes the histogram of grades returned by distribution. def writeHistogram(histogram,write_file): '''(list of int,file opened for writing)-->NoneType Write a histogram of '*'s based on the number of grades in the histogram list. The output format: 0-9: * 10-19: ** 20-29: ****** : 90-99: ** 100: * ''' write_file.write("0-9: ") write_file.write('*' * histogram[0]+str(histogram[0])) write_file.write('\n') # Write the 2-digit ranges. for i in range(1,10): low = i*10 high = low+9 write_file.write(str(low)+'-'+str(high)+': ') write_file.write('*'*histogram[i]+str(histogram[i])) write_file.write('\n') write_file.write("100: ") write_file.write('*' * histogram[-1]+str(histogram[-1])) write_file.write('\n') write_file.close # Self-derived algorithm, have bugs.(Not deleting for further analysis and possible debugging.) # for i in range(0,100,9): # write_file.write(str(i)) # write_file.write('-') # write_file.write(str(i+9)) # write_file.write(':') # write_file.write('*'*histogram[(i//10)]) # write_file.write(str(histogram[(i//10)])) # write_file.write('\n') # write_file.close()
true
67613b888eaa088a69a0fec26f1ace376f95cbbb
ananyo141/Python3
/calListAvg.py
624
4.15625
4
# WAP to return a list of averages of values in each of inner list of grades. # Subproblem: Find the average of a list of values def calListAvg(grades): '''(list of list of num)--list of num Return the list of average of numbers from the list of lists of numbers in grades. >>> calListAvg([[5,2,4,3],[4,6,7,8],[4,3,5,3,4,4],[4,35,3,45],[56,34,3,2,4],[5,3,56,6,7,6]]) [3.5, 6.25, 3.833, 21.75, 19.8, 13.833] ''' avg_list=[] for sublist in grades: total=0 for grade in sublist: total+=grade avg_list.append(total/len(sublist)) return avg_list
true
b7e98df96a4a263667a93d2ae87d397457cd0cb4
ananyo141/Python3
/addColor.py
362
4.1875
4
#WAP to input colors from user and add it to list def addColor(): '''(NoneType)-->list Return the list of colors input by the user. ''' colors=[] prompt="Enter the color you want to add, press return to exit.\n" color=input(prompt) while color!='': colors.append(color) color=input(prompt) return colors
true
6ccdbdcc90fffe223051131e8b7cc1b2c5bb9341
vlytvynenko/lp
/lp_hw/ex8.py
780
4.28125
4
formatter = "{} {} {} {}" #Defined structure of formatter variable #Creating new string based on formatter structure with a new data print(formatter.format(1, 2, 3, 4)) #Creating new string based on formatter structure with a new data print(formatter.format('one', 'two', 'three', 'four')) #Creating new string based on formatter structure with a new data print(formatter.format(True, False, False, True)) #Creating new string based on formatter structure with a formatter variable print(formatter.format(formatter, formatter, formatter, formatter)) #New structure for the last string formatter2 = "{}; {}; {}; {}!" #printed new string based on formatter2 structure print(formatter2.format( "Lya, lya, lya", "Zhu, Zhu, zhu", "Ti podprignizh", "Ya vsazhu" ))
true
738774b4756d730e942bcb8c88ec3801afe4b54c
legitalpha/Spartan
/Day_9_ques1_Russian_peasant_algo.py
285
4.125
4
a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) count = 0 while a!=0: if a%2==1: count +=b b=b<<1 a=a>>1 if a%2==0: b=b<<1 a=a>>1 print("The product of first and second number is ",count)
true
edbbed7b9a0ebeae3e1478b4988008deed3cee2e
dgquintero/holbertonschool-machine_learning
/math/0x03-probability/binomial.py
1,951
4.125
4
#!/usr/bin/env python3 """class Binomial that represents a Binomial distribution""" class Binomial(): """ Class Binomial that calls methos CDF PDF """ def __init__(self, data=None, n=1, p=0.5): """ Class Binomial that calls methos CDF PDF """ self.n = int(n) self.p = float(p) if data is None: if self.n <= 0: raise ValueError("n must be a positive value") elif self.p <= 0 or self.p >= 1: raise ValueError("p must be greater than 0 and less than 1") else: if type(data) is not list: raise TypeError("data must be a list") elif len(data) < 2: raise ValueError("data must contain multiple values") else: mean = sum(data) / len(data) v = 0 for i in range(len(data)): v += ((data[i] - mean) ** 2) variance = v / len(data) self.p = 1 - (variance / mean) self.n = int(round(mean / self.p)) self.p = mean / self.n def pmf(self, k): """Method that returns the pmf""" k = int(k) if k > self.n or k < 0: return 0 factor_k = 1 factor_n = 1 factor_nk = 1 for i in range(1, k + 1): factor_k *= i for i in range(1, self.n + 1): factor_n *= i for f in range(1, (self.n - k) + 1): factor_nk *= f comb = factor_n / (factor_nk * factor_k) prob = (self.p ** k) * ((1 - self.p) ** (self.n - k)) pmf = comb * prob return pmf def cdf(self, k): """ Method that returns the Cumulative Distribution Function""" k = int(k) if k < 0: return 0 else: cdf = 0 for i in range(k + 1): cdf += self.pmf(i) return cdf
true
d5491b784640d17450cbf52b9ecd8019f5b630a7
kvanishree/AIML-LetsUpgrade
/Day4.py
1,393
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[8]: #Q1 print("enter the operation to perform") a=input() if(a=='+'): c=(3+2j)+(5+4j) print(c) elif(a=='-'): c=(3+2j)-(5+4j) print(c) elif(a=='*'): c=(3+2j)*(5+4j) print(c) elif(a=='/'): c=(3+2j)/(5+4j) print(c) elif(a=='//'): print("floor division of two number is not possible\n") elif(a=='%'): print("module is not possible to do in complex numbers\n") else: print("enter correct operation") # #Q2 # range() # range(start,stop,step) # start:it is not compulsory but if we want we can mention this for where to start.. # stop:it is required and compulsory to mention , this for where to stop.. # step: it is not compulsory to mention , but if we requird to print one step forward number of every number.. # # In[21]: #ex for i in range(5): print(i) print("---------------") list=[1,2,3,4,5,6,7] for list in range(1,5,2): print(list) # In[23]: #Q3 a=int(input(print("enter the num1\n"))) b=int(input(print("enter the num1\n"))) c=a-b if(c>25): print("multiplication is = ",a*b) else: print("division is = ",a/b) # In[2]: #Q4 l=[1,2,3,4,5,6] for i in range(len(l)): if(l[i]%2==0): print("square of the number minus 2\n") # In[3]: #Q5 l2=[12,14,16,17,8] for i in range(len(l2)): if (l2[i]/2)>7: print(l2[i],end=" ") # In[ ]:
true
45031662df9be1dafbac90323ea6b977949328f5
Jerwinprabu/practice
/reversepolish.py
596
4.34375
4
#!/usr/bin/python """ reverse polish notation evaluator Functions that define the operators and how to evaluate them. This example assumes binary operators, but this is easy to extend. """ ops = { "+" : (lambda a, b: a + b), "-" : (lambda a, b: a - b), "*" : (lambda a, b: a * b) } def eval(tokens): stack = [] for token in tokens: if token in ops: arg2 = stack.pop() arg1 = stack.pop() result = ops[token](arg1, arg2) stack.append(result) else: stack.append(int(token)) return stack.pop() print "Result:", eval("7 2 3 + -".split())
true
c5363e8be7c3e46cd35561d83880c3162f6ece0f
ataicher/learn_to_code
/careeCup/q14.py~
911
4.3125
4
#!/usr/bin/python -tt import sys def isAnagram(S1,S2): # remove white space S1 = S1.replace(' ',''); S2 = S2.replace(' ','') # check the string lengths are identical if len(S1) != len(S2): return False # set strings to lower case S1 = S1.lower(); S2 = S2.lower() # sort strings S1 = sorted(S1); S2 = sorted(S2) if S1 == S2: return True else: return False def main(): print 'find out if two strings are anagrams' if len(sys.argv) == 3: S1 = sys.argv[1] S2 = sys.argv[2] print 'S1 =', S1 print 'S2 =', S2 else: S1 = 'Namibia' S2 = 'I am a bin' print 'using default strings:\nS1 = Namibia\nS2 = I am a bin' if isAnagram(S1,S2): print 'the two strings are anagrams!' else: print 'sorry. The two strings are not anagrams' # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
true
9317aaa0cb94a12b89f6960525791598088003d6
HeavenRicks/dto
/primary.py
2,273
4.46875
4
#author: <author here> # date: <date here> # --------------- Section 1 --------------- # # ---------- Integers and Floats ---------- # # you may use floats or integers for these operations, it is at your discretion # addition # instructions # 1 - create a print statement that prints the sum of two numbers # 2 - create a print statement that prints the sum of three numbers # 3 - create a print statement the prints the sum of two negative numbers print(7+3) print(3+6+2) print(-5+-7) # subtraction # instructions # 1 - create a print statement that prints the difference of two numbers # 2 - create a print statement that prints the difference of three numbers # 3 - create a print statement the prints the difference of two negative numbers print(10-4) print(24-8-3) print(-9--3) # multiplication and true division # instructions # 1 - create a print statement the prints the product of two numbers # 2 - create a print statement that prints the dividend of two numbers # 3 - create a print statement that evaluates an operation using both multiplication and division print(8*4) print(16/2) print(4*6/2) # floor division # instructions # 1 - using floor division, print the dividend of two numbers. print(24//8) # exponentiation # instructions # 1 - using exponentiation, print the power of two numbers print(18**2) # modulus # instructions # 1 - using modulus, print the remainder of two numbers print(50%7) # --------------- Section 2 --------------- # # ---------- String Concatenation --------- # # concatenation # instructions # 1 - print the concatenation of your first and last name # 2 - print the concatenation of five animals you like # 3 - print the concatenation of each word in a phrase print('Heaven' + 'Ricks') print('Dolphins'+'Pandas'+'Monkeys'+'Goats'+'Horse') print('i'+'love'+'dolphins') # duplication # instructions # 1 - print the duplpication of your first name 5 times # 2 - print the duplication of a song you like 10 times print('heaven'*5) print('solid'*10) # concatenation and duplpication # instructions # 1 - print the concatenation of two strings duplicated 3 times each print('Heaven'+'Ricks'*3)
true
849c615ac2f77f6356650311deea9da6c32952bf
andrearus-dev/shopping_list
/myattempt.py
1,719
4.1875
4
from tkinter import * from tkinter.font import Font window = Tk() window.title('Shopping List') window.geometry("400x800") window.configure(bg="#2EAD5C") bigFont = Font(size=20, weight="bold") heading1 = Label(window, text=" Food Glorious Food \n Shopping List", bg="#2EAD5C", fg="#fff", font=bigFont).pack(pady=10) # Adding input text to the list def add_command(): text = entry_field.get() for item in my_list: list_layout.insert(END, text) # Deleting one item at a time def delete_command(): for item in my_list: list_layout.delete(ACTIVE) # Deleting all items with one click of a button def delete_all_command(): list_layout.delete(0, END) # Variable holding empty list my_list = [""] # Frame and scroll bar so the user can view the whole list my_frame = Frame(window, bg="#00570D") scrollBar = Scrollbar(my_frame, orient=VERTICAL) # List box - where the items will be displayed list_layout = Listbox(my_frame, width=40, height=20, yscrollcommand=scrollBar.set) list_layout.pack(pady=20) # configure scrollbar scrollBar.config(command=list_layout.yview) scrollBar.pack(side=RIGHT, fill=Y) my_frame.pack(pady=20) heading2 = Label(window, text="Add items to your list \n Happy Shopping!", bg="#2EAD5C", fg="#fff", font=1).pack(pady=5) # Entry Field entry_field = Entry(window) entry_field.pack(pady=5) # Buttons - when clicked the function is called Button(window, text="Add Item", command=add_command).pack(pady=5) Button(window, text="Delete Item", command=delete_command).pack(pady=5) Button(window, text="Delete ALL Food Items", command=delete_all_command).pack(pady=10) window.mainloop()
true
026dc30173ab7427f744b000f55558ffc19099e8
glaxur/Python.Projects
/guess_game_fun.py
834
4.21875
4
""" guessing game using a function """ import random computers_number = random.randint(1,100) PROMPT = "What is your guess?" def do_guess_round(): """Choose a random number,ask user for a guess check whether the guess is true and repeat whether the user is correct""" computers_number = random.randint(1,100) while True: players_guess = int(input(PROMPT)) if computers_number == int(players_guess): print("correct!") break elif computers_number > int(players_guess): print("Too low") else: print("Too high") while True: print("Starting a new round") print("The computer's number should be "+str(computers_number)) print("Let the guessing begin!!!") do_guess_round() print(" ")
true
46f70133d8fc36aa8c21c51ba8cd35efd18fcfc7
MenggeGeng/FE595HW4
/hw4.py
1,520
4.1875
4
#part 1: Assume the data in the Boston Housing data set fits a linear model. #When fit, how much impact does each factor have on the value of a house in Boston? #Display these results from greatest to least. from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt import pandas as pd import seaborn as sns #load boston dataset boston = load_boston() #print(boston) data = pd.DataFrame(boston['data'], columns= boston['feature_names']) print(data.head()) data['target'] = boston['target'] print(data.head()) # The correlation map correlation = data.corr() sns.heatmap(data = correlation, annot = True) plt.show() # The correlation coefficient between target and features print(correlation['target']) #prepare the regression objects X = data.iloc[:, : -1] Y = data['target'] print(X.shape) print(Y.shape) #build regression model reg_model = LinearRegression() reg_model.fit(X,Y) print('coefficient : \n ', reg_model.coef_) #The impact of each factor have on the value of a house in Boston coef = pd.DataFrame(data= reg_model.coef_, index = boston['feature_names'], columns=["value"]) print(coef) #Display these results from greatest to least. coef_abs = abs(reg_model.coef_) coef_1 = pd.DataFrame(data= coef_abs , index = boston['feature_names'], columns=["value"]) print("Display these coefficient from greatest to least:") print(coef_1.sort_values("value",inplace=False, ascending=False))
true
9d723b583cec6a1c2ec2aea6497eec0d6dd6d27f
ageinpee/DaMi-Course
/1/Solutions/Solution-DAMI1-Part3.py
2,024
4.15625
4
''' Solution to Part III - Python functions. Comment out the parts you do not wish to execute or copy a specific function into a new py-file''' #Sum of squares, where you can simply use the square function you were given def sum_of_squares(x, y): return square(x) + square(y) print sum_of_squares(3, 5) # Try out yourself #Increment by 1 x = 0 y = 0 def incr(x): y = x + 1 return y print incr(5) # Try out yourself # Increment by any n; quite straightforward, right? x = 0 y = 0 def incr_by_n(x, n): y = x + n return y print incr_by_n(4,2) # Try out yourself #Factorial of a number def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n=int(input("The number you want to compute the factorial of: ")) # User input print "Result:", factorial(4) # Try out yourself #Display numbers between 1 and 10 using 'for' ... for a in range(1, 11): print a #... and 'while' a=1 while a<=10: print a a+=1 #Test if a number is between 1 and 10 (can be of any range though) def number_in_range(n): if n in range(1,10): print( " %s is in the range"%str(n)) else : print "The number is outside the given range." test_range(8) # Try out yourself '''Multiple if-conditionals Note, that no keyword 'end' is needed! Instead, program blocks are controlled via indentation. For beginners, indentation errors are most likely to occur, so playing around and extending smaller code snippets to bigger program code can better help understanding the underlying Python interpretation process''' def chain_conditions(x,y): if x < y: print x, "is less than", y elif x > y: print x, "is greater than", y else: print x, "and", y, "are equal" chain_conditions(50, 10) # Try out yourself #Prime number def test_prime(n): if (n==1): return False elif (n==2): return True; else: for x in range(2,n): if(n % x==0): return False return True print(test_prime(7)) # Try out yourself
true
45fc9452f03b169869eb753bf3ffc017540dd052
sejinwls/2018-19-PNE-practices
/session-5/ex-1.py
620
4.1875
4
def count_a(seq): """"THis function is for counting the number of A's in the sequence""" # Counter for the As result = 0 for b in seq: if b == "A": result += 1 # Return the result return result # Main program s = input("Please enter the sequence: ") na = count_a(s) print("The number of As is : {}".format(na)) # Calculate the total sequence lenght tl = len(s) # Calculate the percentage of As in the sequence if tl > 0: perc = round(100.0 * na/tl, 1) else: perc = 0 print("The total lenght is: {}".format(tl)) print("The percentage of As is {}%".format(perc))
true
e14736ccc657561a7db0a6653d64f05953b85d30
aratik711/100-python-programs
/eval_example.py
320
4.28125
4
""" Please write a program which accepts basic mathematic expression from console and print the evaluation result. Example: If the following string is given as input to the program: 35+3 Then, the output of the program should be: 38 Hints: Use eval() to evaluate an expression. """ exp = input() print(eval(exp))
true
d33e36b0734802ce63caaa7310a21ecb2b6081d6
aratik711/100-python-programs
/subclass_example.py
382
4.125
4
""" Question: Define a class named American and its subclass NewYorker. Hints: Use class Subclass(ParentClass) to define a subclass. """ class American: def printnationality(self): print("America") class NewYorker: def printcity(self): American.printnationality(self) print("New York") citizen = NewYorker() citizen.printcity()
true
f7b05c070eb88efe3ea889c2d77647a6e9cf6b4d
sureshpodeti/Algorithms
/dp/slow/min_cost_path.py
1,157
4.125
4
''' Min cost path: Given a matrix where each cell has some interger value which represent the cost incurred if we visit that cell. Task is found min cost path to reach (m,n) position in the matrix from (0,0) position possible moves: one step to its right, one step down, and one step diagonally brute-force : generate and test Let f(i,j) denote the min cost path needed to reach (i,j) position from (0,0) position Suppose, if we have f(i-1,j), f(i-1, j-1), and f(i, j-1) , Is it possible to find f(i,j) from know values ??? answer: yes, we can as shown below f(i,j) = A[i][j]+min{f(i-1, j-1), f(i-1,j), f(i, j-1)} base condition : if i<0 or j<0 then return 0 if i ==j and i==0 then return A[i][j] ''' from sys import maxint def min_cost_path(A, m,n): if m<0 or n<0: return maxint if m==n and m==0: return A[m][n] return A[m][n]+ min(min_cost_path(A, m-1, n), min_cost_path(A, m-1, n-1), min_cost_path(A, m, n-1)) A = [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ] inp = raw_input().split(' ') m,n = map(int, inp) print "min_cost_path({}):{}".format(A, min_cost_path(A, m, n))
true
e8019a0d7da90f1633bd139a32ca191887b08c10
naroladhar/MCA_101_Python
/mulTable.py
1,074
4.125
4
import pdb pdb.set_trace() def mulTable(num,uIndexLimit): ''' Objective : To create a multiplication table of numbers Input Variables : num : A number uIndexLimit: The size of the multiplication table Output Variables: res : The result of the product return value:none ''' for i in range(0,uIndexLimit+1): res=num*i print("%d X %d = %d" %(num,i,res)) def main(): ''' Objective : To create a multiplication table of numbers Input Variables : num : A number uIndexLimit: The size of the multiplication table Output Variables: res : The result of the product return value:none ''' start=int(input(" Enter a start: ")) finish = int(input(" Enter a finish: ")) uIndexLimit = int(input(" Enter size of the table: ")) for start in range(start,finish+1): print("*******Time Table for ",start,"*********") mulTable(start,uIndexLimit) if __name__=='__main__': main()
true
92aca135af4da75cb0cd32b9bfac71515384e04d
hakanguner67/class2-functions-week04
/exact_divisor.py
376
4.125
4
''' Write a function that finds the exact divisors of a given number. For example: function call : exact_divisor(12) output : 1,2,3,4,6,12 ''' #users number number = int(input("Enter a number : ")) def exact_divisor(number) : i = 1 while i <= number : # while True if ((number % i )==0) : print (i) i = i + 1 exact_divisor(number)
true
89aa00e1cd5480b1e976fe94a3bbd044f8f671de
hakanguner67/class2-functions-week04
/counter.py
590
4.21875
4
''' Write a function that takes an input from user and than gives the number of upper case letters and smaller case letters of it. For example : function call: counter("asdASD") output: smaller letter : 3 upper letter : 3 ''' def string_test(s): upper_list=[] smaller_list=[] for i in s: if i.isupper(): upper_list.append(i) elif i.islower(): smaller_list.append(i) else : pass print("Smaller Letter : ",len(smaller_list)) print("Upper Letter :",len(upper_list)) s = input("Enter a word : ") string_test(s)
true
38ed49911be4adb634aa662aed898a56c244c5ac
mariadiaz-lpsr/class-samples
/5-4WritingHTML/primeListerTemplate.py
944
4.125
4
# returns True if myNum is prime # returns False is myNum is composite def isPrime(x, myNum): # here is where it will have a certain range from 2 to 100000 y = range(2,int(x)) # subtract each first to 2 primenum = x - 2 count = 0 for prime in y: # the number that was divided will then be divided to find remainder rem_prime = int(x) % int(prime) if rem_prime != 0: count = count + 1 # if it is prime it will print it and append it to the ListOfPrime if count == primenum: print(x) myNum.append(x) ListOfPrime = [] # the file numbers.txt will open so it can be append the numbers that are prime only prime = open("numbers.txt", "w") # the range is from 2 to 100000 r = range(2, 100000) for PList in r: numberss = isPrime(PList, ListOfPrime) for y in ListOfPrime: # the prime numbers will be written in a single list prime.write(str(y) + "\n") # the file that was open "numbers.txt" will close prime.close()
true
120526d1004799d849367a701f6fa9c09c6bbe05
mariadiaz-lpsr/class-samples
/quest.py
1,314
4.15625
4
print("Welcome to Maria's Quest!!") print("Enter the name of your character:") character = raw_input() print("Enter Strength (1-10):") strength = int(input()) print("Enter Health (1-10):") health = int(input()) print("Enter Luck (1-10):") luck = int(input()) if strength + health + luck > 15: print("You have give your character too many points! ") while strength + health + luck < 15: print(character , "strength" + strength + "health" + health + "luck" + luck) if strength + health + luck == 15: print(character," you've come to a fork in the road. Do you want to go right or left? Enter right or left. ") if right or left == "left": print("Sorry you lost the game.") # if user chooses right and has strength over 7 if strength >= 7: print(character,"you're strength is high enough you survived to fight the ninjas that attacked you. You won the game!") else: print("You didn't have sufficient strength to defeat the ninjas. Sorry you lost the game :(. ") # if health is greater than 8 if health >= 8: print("You had enough energy to pass by the ninjas." else: print("Sorry your health was not enough to survive the spriral ninja stars wound. ") # if the number of luck is greater than 5 it wil print out the first line if not it will directly go to the else line if luck >= 5: print("You had ")
true
7251ebc79e8c4968588276efb33d05320b032750
mariadiaz-lpsr/class-samples
/names.py
1,010
4.3125
4
# it first prints the first line print("These are the 5 friends and family I spend the most time with: ") # these are the 2 list name names and nams names = ['Jen', 'Mom', 'Dad', 'Alma', 'Ramon'] nams = ['Jackelyn', 'Judy', 'Elyssa', 'Christina', 'Cristian'] # it is concatenating both of the lists names_nams = names + nams # its changing the word in that number to another thing to print out instead for nms in names: names[0] = "1. Jen" for nms in names: names[1] = "2. Mom" for nms in names: names[2] = "3. Dad" for nms in names: names[3] = "4. Alma" for nms in names: names[4] = "5. Ramon" for nms in names: names[5] = "6. Jackelyn" for nms in names: names[6] = "7. Judy" for nms in names: names[7] = "8. Elyssa" for nms in names: names[8] = "9. Christina" for nms in names: names[9] = "10. Cristian" # it will print out both the names and nams lists print(names_nams) # it will reverse the list names.reverse() # it will print out the list been in reverse order print(names_nams)
true
434182c9ca2fa8b73c4f2fd0b4d9197720b7d406
pktippa/hr-python
/basic-data-types/second_largest_number.py
430
4.21875
4
# Finding the second largest number in a list. if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) # Converting input string into list by map and list() new = [x for x in arr if x != max(arr)] # Using list compressions building new list removing the highest number print(max(new)) # Since we removed the max number in list, now the max will give the second largest from original list.
true
3c09d0c67801c8748794d163a275a6c6f5b88378
pktippa/hr-python
/itertools/permutations.py
678
4.15625
4
# Importing permutations from itertools. from itertools import permutations # Taking the input split by space into two variables. string, count = input().split() # As per requirement the given input is all capital letters and the permutations # need to be in lexicographic order. Since all capital letters we can directly use # sorted(str) and join to form string string = ''.join(sorted(string)) # Calling permutations to get the list of permutations, returns list of tuples permutation_list = list(permutations(string, int(count))) # Looping through all elements(tuples) for element in permutation_list: print(''.join(element)) # forming string from a tuple of characters
true
e03cc807d94143ba7377b192d5784cbdb07b1abd
pktippa/hr-python
/math/find_angle_mbc.py
376
4.34375
4
# importing math import math # Reading AB a = int(input()) # Reading BC b = int(input()) # angle MBC is equal to angle BCA # so tan(o) = opp side / adjacent side t = a/b # calculating inverse gives the value in radians. t = math.atan(t) # converting radians into degrees t = math.degrees(t) # Rounding to 0 decimals and adding degree symbol. print(str(int(round(t,0))) + '°')
true
bed0fc094ed0b826db808aa4449cbf31686cbd2a
aryakk04/python-training
/functions/dict.py
549
4.53125
5
def char_dict (string): """ Prints the dictionary which has the count of each character occurrence in the passed string argument Args: String: It sould be a string from which character occurrence will be counted. Returns: Returns dictionary having count of each character in the given string. """ char_dic = {} for char in string: if char not in char_dic: char_dic[char] = string.count(char) return char_dic string = input("Enter a string : ") char_dic = char_dict (string) print (char_dic)
true
2e0deae0231338db84a2f11cd64994bf82900b33
seanakanbi/SQAT
/SampleTests/Sample/classes/Calculator.py
1,677
4.375
4
import math from decimal import * class Calculator(): """ A special number is any number that is - is between 0 and 100 inclusive and - divisible by two and - divisible by five. @param number @return message (that displays if the number is a special number) """ def is_special_number(self, num_in): # Verify the number is within the valid range. if num_in < 0 or num_in > 100: message = " is not a valid number." else: # Determine if the number is a special number. if num_in % 2 != 0: message = " is not an even number." elif num_in % 5 != 0: message = " is not divisible by five." else: message = " is a special number" #Remember this will return your number plus the message! return str(num_in) + message """ This method does a strange/alternative calculation * @param operand * @return calculated value as a Decimal """ def alternative_calculate(self, operand): calculated_value = operand * 100 / math.pi return Decimal(calculated_value) if __name__ == '__main__': print("****** ******* ") print("****** Running calculator ******* ") calc = Calculator() num1 = int(input("Please enter a number to check if it is special: " )) print("-> ", calc.is_special_number(num1)) num2 = int(input("Please enter a number to run an alternative calculation on it: " )) print("-> ", round(calc.alternative_calculate(num2),4))
true
0df98d530f508a752e42a67ad7c6fe0a2608f823
JaiAmoli/Project-97
/project97.py
266
4.21875
4
print("Number Guessing Game") print("guess a number between 1-9") number = int(input("enter your guess: ")) if(number<2): print("your guess was too low") elif(number>2): print("your guess was too high") else: print("CONGRATULATIONS YOU WON!!!")
true
7b9c3c2cd1a9f753a9f3df2adeb84e846c9eb1b4
mschaldias/programmimg-exercises
/list_merge.py
1,395
4.34375
4
''' Write an immutable function that merges the following inputs into a single list. (Feel free to use the space below or submit a link to your work.) Inputs - Original list of strings - List of strings to be added - List of strings to be removed Return - List shall only contain unique values - List shall be ordered as follows --- Most character count to least character count --- In the event of a tie, reverse alphabetical Other Notes - You can use any programming language you like - The function you submit shall be runnable For example: Original List = ['one', 'two', 'three',] Add List = ['one', 'two', 'five', 'six] Delete List = ['two', 'five'] Result List = ['three', 'six', 'one']* ''' def merge_lists(start_list,add_list,del_list): set_start = set(start_list) set_add = set(add_list) set_del = set(del_list) set_final = (set_start | set_add) - set_del final_list = list(set_final) final_list.sort(key=len, reverse=True) return final_list def main(): start_list = ['one', 'two', 'three',] add_list = ['one', 'two', 'five', 'six'] del_list = ['two', 'five'] #final_list = ['three', 'six', 'one'] final_list = merge_lists(start_list,add_list,del_list) print(final_list) main()
true
d089ecb536c7d01e7387f82dbe93da65da98358c
yogabull/TalkPython
/WKUP/loop.py
925
4.25
4
# This file is for working through code snippets. ''' while True: print('enter your name:') name = input() if name == 'your name': break print('thank you') ''' """ name = '' while name != 'your name': name = input('Enter your name: ') if name == 'your name': print('thank you') """ import random print('-----------------') print(' Number Game') print('-----------------') number = random.randint(0, 100) guess = '' while guess != number: guess = int(input('Guess a number between 1 and 100: ')) if guess > number: print('Too high') print(number) if guess < number: print('Too low') print(number) if guess == number: print('Correct') print(number) print('---------------------') print(' f-strings') print('---------------------') name = input('Please enter your name: ') print(f'Hi {name}, it is nice to meet you.')
true
ce930feff941e3e78f9629851ce0c8cc08f8106b
yogabull/TalkPython
/WKUP/fStringNotes.py
694
4.3125
4
#fString exercise from link at bottom table = {'John' : 1234, 'Elle' : 4321, 'Corbin' : 5678} for name, number in table.items(): print(f'{name:10} --> {number:10d}') # John --> 1234 # Elle --> 4321 # Corbin --> 5678 ''' NOTE: the '10' in {name:10} means make the name variable occupy at least 10 spaces. This is useful for making columns align. ''' ''' f-Strings: Another method to output varibles within in a string. Formatted String Literals This reads easily. year = 2019 month = 'June' f'It ends {month} {year}.' >>> It ends June 2019. https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings '''
true
c7fc3ced3296f7e181ba9714534800b59d20dd53
thevirajshelke/python-programs
/Basics/subtraction.py
586
4.25
4
# without user input # using three variables a = 20 b = 10 c = a - b print "The subtraction of the numbers is", c # using 2 variables a = 20 b = 10 print "The subtraction of the numbers is", a - b # with user input # using three variables a = int(input("Enter first number ")) b = int(input("Enter first number ")) c = a - b print "The subtraction of the numbers is", c # using 2 variables # int() - will convert the input into numbers if string is passed! a = int(input("Enter first number ")) b = int(input("Enter first number ")) print "The subtraction of the numbers is", a - b
true
ef45e2377ab4276345644789a17abdd20da69aca
johnehunt/computationalthinking
/week4/tax_calculator.py
799
4.3125
4
# Program to calculate tax band print('Start') # Set up 'constants' to be used BASIC_RATE_THRESHOLD = 12500 HIGHER_RATE_THRESHOLD = 50000 ADDITIONAL_RATE_THRESHOLD = 150000 # Get user input and a number income_string = input('Please input your income: ') if income_string.isnumeric(): annual_income = int(income_string) # Determine tax band if annual_income > ADDITIONAL_RATE_THRESHOLD: print('Calculating tax ...') print('Your highest tax rate is 45%') elif annual_income > HIGHER_RATE_THRESHOLD: print('Your highest tax rate is 40%') elif annual_income > BASIC_RATE_THRESHOLD: print('Your highest tax rate is 20%') else: print('You are not liable for income tax') else: print('Input must be a positive integer') print('Done')
true
8d7ca111c403010de98909a1850ae5f7a1d54b2b
johnehunt/computationalthinking
/number_guess_game/number_guess_game_v2.py
1,262
4.34375
4
import random # Print the Welcome Banner print('===========================================') print(' Welcome to the Number Guess Game') print(' ', '-' * 40) print(""" The Computer will ask you to guess a number between 1 and 10. """) print('===========================================') # Initialise the number to be guessed number_to_guess = random.randint(1, 10) # Set up flag to indicate if one game is over finished_current_game = False # Obtain their initial guess and loop to see if they guessed correctly while not finished_current_game: guess = None # Make sure input is a positive integer input_ok = False while not input_ok: input_string = input('Please guess a number between 1 and 10: ') if input_string.isdigit(): guess = int(input_string) input_ok = True else: print('Input must be a positive integer') # Check to see if the guess is above, below or the correct number if guess < number_to_guess: print('Your guess was lower than the number') elif guess > number_to_guess: print('Your guess was higher than the number') else: print('Well done you won!') finished_current_game = True print('Game Over')
true
0f25b7552ca48fbdc04ee31bd873d899ffae26c6
johnehunt/computationalthinking
/week4/forsample.py
813
4.34375
4
# Loop over a set of values in a range print('Print out values in a range') for i in range(0, 10): print(i, ' ', end='') print() print('Done') print('-' * 25) # Now use values in a range but increment by 2 print('Print out values in a range with an increment of 2') for i in range(0, 10, 2): print(i, ' ', end='') print() print('Done') print('-' * 25) # This illustrates the use of a break statement num = int(input('Enter a number: ')) for i in range(0, 6): if i == num: break print(i, ' ', end='') print('Done') print('-' * 25) # This illustrates the use of a continue statement for i in range(0, 10): print(i, ' ', end='') if i % 2 == 1: # Determine if this is an odd number continue print('its an even number') print('we love even numbers') print('Done')
true
2acb0005b760b130fc4c553b8f9595c91b828c0e
tainagdcoleman/sharkid
/helpers.py
2,892
4.125
4
from typing import Tuple, List, Dict, TypeVar, Union import scipy.ndimage import numpy as np import math Num = TypeVar('Num', float, int) Point = Tuple[Num, Num] def angle(point: Point, point0: Point, point1: Point) -> float: """Calculates angles between three points Args: point: midpoint point0: first endpoint point1: second endpoint Returns: angle between three points in radians """ a = (point[0] - point0[0], point[1] - point0[1]) b = (point[0] - point1[0], point[1] - point1[1]) adotb = (a[0] * b[0] + a[1] * b[1]) return math.acos(adotb / (magnitude(a) * magnitude(b))) def find_angles(points: List[Point])-> List[float]: """Finds angles between all points in sequence of points Args: points: sequential list of points Returns: angles in radians """ return angle(points[len(points) // 2], points[0], points[-1]) def magnitude(point: Point) -> float: """Finds the magnitude of a point, as if it were a vector originating at 0, 0 Args: point: Point (x, y) Returns: magnitude of point """ return math.sqrt(point[0]**2 + point[1]**2) def dist_to_line(start: Point, end: Point, *points: Point, signed=False) -> Union[float, List[float]]: """Finds the distance between points and a line given by two points Args: start: first point for line end: second point for line points: points to find distance of. Returns: A single distance if only one point is provided, otherwise a list of distances. """ start_x, start_y = start end_x, end_y = end dy = end_y - start_y dx = end_x - start_x m_dif = end_x*start_y - end_y*start_x denom = math.sqrt(dy**2 + dx**2) _dist = lambda point: (dy*point[0] - dx*point[1] + m_dif) / denom dist = _dist if signed else lambda point: abs(_dist(point)) if len(points) == 1: return dist(points[0]) else: return list(map(dist, points)) def gaussian_filter(points:List[Point], sigma=0.3): return scipy.ndimage.gaussian_filter(np.asarray(points), sigma) def distance(point1: Point, point2: Point): x1, y1 = point1 x2, y2 = point2 return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) def coord_transform(points: List[Tuple[int, int]])-> float: start_x, start_y = points[0] end_x, end_y = points[-1] inner = points[1:-1] perp_point_x = start_x - (end_y - start_y) perp_point_y = start_y + (end_x - start_x) ys = dist_to_line((start_x, start_y), (end_x, end_y), *inner, signed=True) xs = dist_to_line((start_x, start_y), (perp_point_x, perp_point_y), *inner, signed=True) return xs, ys def remove_decreasing(xs, ys): maxx = xs[0] for x, y in zip(xs, ys): if x > maxx: yield x, y maxx = x
true
419e9c5cbb652df0abccd13ca68273bc18327cd9
jadugnap/python-problem-solving
/Task4-predict-telemarketers.py
1,300
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. text.csv columns: sending number (string), receiving number (string), message timestamp (string). call.csv columns: calling number (string), receiving number (string), start timestamp (string), duration in seconds (string) """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ text_senders = set([t[0] for t in texts]) text_receivers = set([t[1] for t in texts]) call_receivers = set([c[1] for c in calls]) whitelist = call_receivers.union(text_senders, text_receivers) # print("\n".join(sorted(whitelist))) callers = sorted(set([c[0] for c in calls if c[0] not in whitelist])) print("These numbers could be telemarketers: ") print("\n".join(callers))
true
a4b024fe5edf1f5da39078c8d52034ba303a98cc
schirrecker/Math
/Math with Python.py
397
4.15625
4
from fractions import Fraction try: a = Fraction(input("Enter a fraction: ")) b = Fraction(input("Enter another fraction: ")) except ValueError: print ("You entered an invalid number") except ZeroDivisionError: print ("You can't divide by zero") else: print (a+b) def is_factor (a, b): if b % a == 0: return True else: return False
true
9fa0e009c15e00016bfae128e68515f6aaa87e5d
rohanyadav030/cp_practice
/is-digit-present.py
865
4.1875
4
# Python program to print the number which # contain the digit d from 0 to n # Returns true if d is present as digit # in number x. def isDigitPresent(x, d): # Breal loop if d is present as digit if (x > 0): if (x % 10 == d): return(True) else: return(False) else: return(False) # function to display the values def printNumbers(n, d): # Check all numbers one by one for i in range(0, n+1): # checking for digit if (i == d or isDigitPresent(i, d)): print(i,end=" ") # Driver code n = 20 d = 5 print("n is",n) print("d is",d) print("The number of values are") printNumbers(n, d) ''' ******************* output ********************** n is 47 d is 7 The number of values are 7 17 27 37 47 n is 20 d is 5 The number of values are 5 15 '''
true
18bde0bbb7b8f371cbbab5d3a73310f823fa3570
amrutha1352/4040
/regularpolygon.py
280
4.28125
4
In [46]: X= float(input("Enter the length of any side: ")) Y= int(input("Enter the number of sides in the regular polygon: ")) import math numerator= math.pow(X,2)*Y denominator= 4*(math.tan(math.pi/Y)) area= numerator/denominator print("The area of the regular polygon is:",area)
true
34c467f6bcb628d403321d30b29644d35af003f3
jonesm1663/cti110
/cti 110/P3HW2.py
543
4.28125
4
# CTI-110 # P3HW2 - Shipping Charges # Michael Jones # 12/2/18 #write a program tha asks the user to enter the weight of a package #then display shipping charges weightofpackage = int(input("Please enter the weight of the package:")) if weightofpackage<= 2: shippingcharges = 1.50 elif weightofpackage < 7: shippingcharges = 3.00 elif weightofpackage < 11: shippingcharges = 4.00 else:shippingcharges = 4.75 print("package weighs"+str(weightofpackage)+", you pay"+ \ format(shippingcharges,",.2f"))
true
619ebd59a6875ca0c6feb9a2074ba5412215c4ae
jonesm1663/cti110
/cti 110/P3HW1.py
820
4.4375
4
# CTI-110 # P3HW1 - Roman Numerals # Michael Jones # 12/2/18 #Write a program that prompts the user to enter a number within the range of 1-10 #The program should display the Roman numeral version of that number. #If the number is outside the range of 1-10, the program should display as error message. userNumber = int(input("Please enter a number")) if userNumber ==1: print("1") elif userNumber ==2: print("II") elif userNumber ==3: print("III") elif userNumber ==4: print("IV") elif userNumber ==5: print("V") elif userNumber ==6: print("VI") elif userNumber ==7: print("VII") elif userNumber ==8: print("VIII") elif userNumber ==9: print("IX") elif userNumber ==10: print("X") else: print("Error: Please enter a number between 1 and 10.")
true
698b8212c16b1a11a5fb9d63af5db687d404039f
beyzakilickol/week1Friday
/algorithms.py
953
4.1875
4
#Write a program which will remove duplicates from the array. arr = ['Beyza', 'Emre', 'John', 'Emre', 'Mark', 'Beyza'] arr = set(arr) arr = list(arr) print(arr) #-------Second way------------------------ remove_dups = [] for i in range(0, len(arr)): if arr[i] not in remove_dups: remove_dups.append(arr[i]) print(remove_dups) #-------------Assignment 2------------------------- #Write a program which finds the largest element in the array arr = [3,5,7,8,9,14,24,105] print(max(arr)) #-------------Assignment 3-------------------------------- #Write a program which finds the smallest element in the array print(min(arr)) # stringArr = ['beyza', 'cem', 'ramazan', 'ak', 'ghrmhffjhfd', 'yep'] # print(min(stringArr)) # returns ak in alphabetical order #------------Assigment 4---------------------------------- #Write a program to display a pyramid string = "*" for i in range(1, 18 , 2): print('{:^50}'.format(i * string))
true
32f05d2f45e3bad3e2014e1ba768a6b92d4e67b6
soumyadc/myLearning
/python/statement/loop-generator.py
575
4.3125
4
#!/usr/bin/python # A Generator: # helps to generate a iterator object by adding 1-by-1 elements in iterator. #A generator is a function that produces or yields a sequence of values using yield method. def fibonacci(n): #define the generator function a, b, counter = 0, 1, 0 # a=0, b=1, counter=0 while True: if(counter > n): return yield a a=b b=a+b counter += 1 it=fibonacci(5) # it is out iterator object here while True: try: print (next(it)) except: break print("GoodBye")
true
7400c080f5ce15b3a5537f436e3458772b42d801
soumyadc/myLearning
/python/tkinter-gui/hello.py
737
4.21875
4
#!/usr/bin/python from Tkinter import * import tkMessageBox def helloCallBack(): tkMessageBox.showinfo( "Hello Python", "Hello World") # Code to add widgets will go here... # Tk root widget, which is a window with a title bar and other decoration provided by the window manager. # The root widget has to be created before any other widgets and there can only be one root widget. top = Tk() L1= Label(top, text="Hello World") L1.pack(side=LEFT) # Button, when clicked it calls helloCallBack() function B1=Button(top, text="Hello", command=helloCallBack) B1.pack(side=RIGHT) # The window won't appear until we enter the Tkinter event loop # Our script will remain in the event loop until we close the window top.mainloop()
true
7b3a4e66395735192270abc17f1c77bc8d5ee5bd
newjoseph/Python
/Kakao/String/parentheses.py
2,587
4.1875
4
# -*- coding: utf-8 -*- # parentheses example def solution(p): #print("solution called, p is: " + p + "\n" ) answer = "" #strings and substrings #w = "" u = "" v = "" temp_str = "" rev_str = "" #number of parentheses left = 0 right = 0 count = 0 # flag correct = True; #step 1 #if p is an empty string, return p; if len(p) == 0: #print("empty string!") return p # step 2 #count the number of parentheses for i in range(0, len(p)): if p[i] == "(" : left += 1 else: right += 1 # this is the first case the number of left and right are the same if left == right: u = p[0: 2*left] v = p[2*left:] #print("u: " + u) #print("v: " + v) break # check this is the correct parenthese () for i in range(0, len(u)): #count the number of "(" if u[i] == "(": count += 1 # find ")" else: # if the first element is not "(" if count == 0 and i == 0 : #print("u: "+ u +" change to false") correct = False break # reduce the number of counter count -= 1 if count < 0: correct = False break; else: continue """ for j in range(1, count + 1): print("i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count) + " lenth of u is " + "{}".format(len(u))) # #if u[i+j] == "(" : if count < 0: print( " change to false " + "i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count)) correct = False break else: continue """ # reset the counter count = 0 #print( "u: " + u + " v: " + v) #if the string u is correct if correct == True: temp = u + solution(v) #print(" u is " + u +" CORRECT! and return: " + temp) return temp # if the string u is not correct else: #print(" u is " + u +" INCORRECT!") #print("check: " + check) temp_str = "(" + solution(v) + ")" # remove the first and the last character temp_u = u[1:len(u)-1] # change parentheses from ( to ) and ) to ( for i in range(len(temp_u)): if temp_u[i] == "(": rev_str += ")" else: rev_str += "(" #print("temp_str: " + temp_str + " rev_str: " + rev_str) answer = temp_str + rev_str #print("end! \n") return answer
true
40834ff71cc6200a7028bd1d8a7cacf42c9f886e
nicolaetiut/PLPNick
/checkpoint1/sort.py
2,480
4.25
4
"""Sort list of dictionaries from file based on the dictionary keys. The rule for comparing dictionaries between them is: - if the value of the dictionary with the lowest alphabetic key is lower than the value of the other dictionary with the lowest alphabetic key, then the first dictionary is smaller than the second. - if the two values specified in the previous rule are equal reapply the algorithm ignoring the current key. """ import sys def quicksort(l): """Quicksort implementation using list comprehensions >>> quicksort([1, 2, 3]) [1, 2, 3] >>> quicksort('bac') ['a', 'b', 'c'] >>> quicksort([{'bb': 1, 'aa': 2}, {'ba': 1, 'ab': 2}, {'aa': 1, 'ac': 2}]) [{'aa': 1, 'ac': 2}, {'aa': 2, 'bb': 1}, {'ab': 2, 'ba': 1}] >>> quicksort([]) [] """ if l == []: return [] else: pivot = l[0] sub_list = [list_element for list_element in l[1:] if list_element < pivot] lesser = quicksort(sub_list) sub_list = [list_element for list_element in l[1:] if list_element >= pivot] greater = quicksort(sub_list) return lesser + [pivot] + greater def sortListFromFile(fileName, outputFileName): """Sort list of dictionaries from file. The input is a file containing the list of dictionaries. Each dictionary key value is specified on the same line in the form <key> <whitespace> <value>. Each list item is split by an empty row. The output is a file containing a list of integers specifying the dictionary list in sorted order. Each integer identifies a dictionary in the order they were received in the input file. >>> sortListFromFile('nonexistentfile','output.txt') Traceback (most recent call last): ... IOError: [Errno 2] No such file or directory: 'nonexistentfile' """ l = [] with open(fileName, 'r') as f: elem = {} for line in f: if line.strip(): line = line.split() elem[line[0]] = line[1] else: l.append(elem) elem = {} l.append(elem) f.closed with open(outputFileName, 'w+') as f: for list_elem in quicksort(l): f.write(str(l.index(list_elem)) + '\n') f.closed if __name__ == "__main__": if (len(sys.argv) > 1): sortListFromFile(sys.argv[1], 'output.txt') else: print "Please provide an input file as argument."
true
4fe12c2ab9d4892088c5270beb6e2ce5d96debb1
chapman-cs510-2016f/cw-03-datapanthers
/test_sequences.py
915
4.3125
4
#!/usr/bin/env python import sequences # this function imports the sequences.py and tests the fibonacci function to check if it returns the expected list. def test_fibonacci(): fib_list=sequences.fibonacci(5) test_list=[1,1,2,3,5] assert fib_list == test_list # ### INSTRUCTOR COMMENT: # It is better to have each assert run in a separate test function. They are really separate tests that way. # Also, it may be more clear in this case to skip defining so many intermediate variables: # assert sequences.fibonacci(1) == [1] # fib_list=sequences.fibonacci(1) test_list=[1] assert fib_list == test_list fib_list=sequences.fibonacci(10) test_list=[1,1,2,3,5,8,13,21,34,55] assert fib_list == test_list # test to make sure negative input works fib_list=sequences.fibonacci(-5) test_list=[1,1,2,3,5] assert fib_list == test_list
true
bd7938eb01d3dc51b4c5a29b68d9f4518163cc92
jguarni/Python-Labs-Project
/Lab 5/prob2test.py
721
4.125
4
from cisc106 import * def tuple_avg_rec(aList,index): """ This function will take a list of non-empty tuples with integers as elements and return a list with the averages of the elements in each tuple using recursion. aList - List of Numbers return - List with Floating Numbers """ newList = [] if len(aList) == 0: return 0 if (len(aList) != index): newList.append((sum(aList[index])/len(aList[index]))) newList.extend((sum(aList[index])/len(aList[index]))) print(aList[index]) tuple_avg_rec(aList, index+1) return newList assertEqual(tuple_avg_rec(([(4,5,6),(1,2,3),(7,8,9)]),0),[5.0, 2.0, 8.0])
true
8656ff504d98876c89ead36e7dd4cc73c3d2249e
jlopezmx/community-resources
/careercup.com/exercises/04-Detect-Strings-Are-Anagrams.py
2,923
4.21875
4
# Jaziel Lopez <juan.jaziel@gmail.com> # Software Developer # http://jlopez.mx words = {'left': "secured", 'right': "rescued"} def anagram(left="", right=""): """ Compare left and right strings Determine if strings are anagram :param left: :param right: :return: """ # anagram: left and right strings have been reduced to empty strings if not len(left) and not len(right): print("Anagram!") return True # anagram not possible on asymetric strings if not len(left) == len(right): print("Impossible Anagram: asymetric strings `{}`({}) - `{}`({})".format(left, len(left), right, len(right))) return False # get first char from left string # it should exist on right regardless char position # if first char from left does not exist at all in right string # anagram is not possible char = left[0] if not has_char(right, char): print("Impossible Anagram: char `{}` in `{}` not exists in `{}`".format(char, left, right)) return False left = reduce(left, char) right = reduce(right, char) if len(left) and len(right): print("After eliminating char `{}`\n `{}` - `{}`\n".format(char, left, right)) else: print("Both strings have been reduced\n") # keep reducing left and right strings until empty strings # anagram is possible when left and right strings are reduced to empty strings anagram(left, right) def has_char(haystack, char): """ Determine if a given char exists in a string regardless of the position :param haystack: :param char: :return: """ char_in_string = False for i in range(0, len(haystack)): if haystack[i] == char: char_in_string = True break return char_in_string def reduce(haystack, char): """ Return a reduced string after eliminating `char` from original haystack :param haystack: :param char: :return: """ output = "" char_times_string = 0 for i in range(0, len(haystack)): if haystack[i] == char: char_times_string += 1 if haystack[i] == char and char_times_string > 1: output += haystack[i] if haystack[i] != char: output += haystack[i] return output print("\nAre `{}` and `{}` anagrams?\n".format(words['left'], words['right'])) anagram(words['left'], words['right']) # How to use: # $ python3 04-Detect-Strings-Are-Anagrams.py # # Are `secured` and `rescued` anagrams? # # After eliminating char `s` # `ecured` - `recued` # # After eliminating char `e` # `cured` - `rcued` # # After eliminating char `c` # `ured` - `rued` # # After eliminating char `u` # `red` - `red` # # After eliminating char `r` # `ed` - `ed` # # After eliminating char `e` # `d` - `d` # # Both strings have been reduced # # Anagram! # # Process finished with exit code 0
true
846cc6cd0915328b64f83d50883167e0d0910f6a
Teju-28/321810304018-Python-assignment-4
/321810304018-Python assignment 4.py
1,839
4.46875
4
#!/usr/bin/env python # coding: utf-8 # ## 1.Write a python function to find max of three numbers. # In[5]: def max(): a=int(input("Enter num1:")) b=int(input("Enter num2:")) c=int(input("Enter num3:")) if a==b==c: print("All are equal.No maximum number") elif (a>b and a>c): print("Maximum number is:",a) elif (b>c and b>a): print("Maximum number is:",b) else: print("Maximum number is:",c) max() # ## 2.Write a python program to reverse a string. # In[6]: def reverse_string(): A=str(input("Enter the string:")) return A[::-1] reverse_string() # ## 3.write a python function to check whether the number is prime or not. # In[13]: def prime(): num=int(input("Enter any number:")) if num>1: for i in range(2,num): if (num%i==0): print(num ,"is not a prime number") break else: print(num ,"is a prime number") else: print(num ,"is not a prime number") prime() # ## 4.Use try,except,else and finally block to check whether the number is palindrome or not. # In[25]: def palindrome(): try: num=int(input("Enter a number")) except Exception as ValueError: print("Invalid input enter a integer") else: temp=num rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 if(temp==rev): print("The number is palindrome") else: print("Not a palindrome") finally: print("program executed") palindrome() # ## 5.Write a python function to find sum of squares of first n natural numbers # In[27]: def sum_of_squares(): n=int(input("Enter the number")) return (n*(n+1)*(2*n+1))/6 sum_of_squares()
true
a9169a0606ef75c17087acce0c610bb5aa8e1660
vivek28111992/DailyCoding
/problem_#99.py
624
4.1875
4
""" Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ def largestElem(arr): s = set(arr) m = 0 for i in range(len(arr)): if arr[i]+1 in s: j = arr[i] m1 = 0 while j in s: j += 1 m1 += 1 m = max(m, m1) print(m) return m if __name__ == "__main__": largestElem([100, 4, 200, 1, 3, 2])
true
f96e8a52c38e140ecf3863d1ea138e15b78c7aa8
vivek28111992/DailyCoding
/problem_#28_15032019.py
1,687
4.125
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Palantir. Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified. More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left. If you can only fit one word on a line, then you should pad the right-hand side with spaces. Each word is guaranteed not to be longer than k. For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following: ["the quick brown", # 1 extra space on the left "fox jumps over", # 2 extra spaces distributed evenly "the lazy dog"] # 4 extra spaces distributed evenly https://leetcode.com/problems/text-justification/discuss/24891/Concise-python-solution-10-lines. """ def fulljustify(words, maxWidth): res, cur, num_of_letters = [], [], 0 for w in words: if num_of_letters + len(w) + len(cur) > maxWidth: for i in range(maxWidth - num_of_letters): cur[i%(len(cur)-1 or 1)] += ' ' res.append(''.join(cur)) cur, num_of_letters = [], 0 cur += [w] num_of_letters += len(w) return res + [' '.join(cur).ljust(maxWidth)] words = ["the quick brown", "fox jumps over", "the lazy dog"] print(fulljustify(words, 16))
true
c80b26a41d86ec4f2f702aab0922b86eec368e84
Brucehanyf/python_tutorial
/file_and_exception/file_reader.py
917
4.15625
4
# 读取圆周率 # 读取整个文件 # with open('pi_digits.txt') as file_object: # contents = file_object.read() # print(contents) # file_path = 'pi_digits.txt'; # \f要转义 # 按行读取 file_path = "D:\PycharmProjects\practise\\file_and_exception\pi_digits.txt"; # with open(file_path) as file_object: # for line in file_object: # print(line) # file_object.readlines() # with open(file_path) as file_object: # lines = file_object.readlines() # for line in lines: # print(line) # 使用文件中的内容 with open(file_path) as file_object: lines = file_object.readlines() result = ''; for line in lines: result += line.strip() print(result) print(result[:10]+'......') print(len(result)) birthday = input('请输入您的生日') if birthday in result: print("your birthday appears in pai digits") else: print("your birthday does not appears in pai digits")
true
62bd9b81b6ace8f9bab84fb293710c50ca0bcf29
thekevinsmith/project_euler_python
/4/largest_palindrome_product.py
1,778
4.125
4
# Problem 4 : Statement: # A palindromic number reads the same both ways. The largest palindrome # made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. def main(): largest = 0 for i in range(0, 1000, 1): count = 0 Num = i while Num > 0: Num = Num//10 count += 1 if count == 3: prodNum.append(i) for p in range(len(prodNum)): for n in range(len(prodNum)): result = prodNum[p] * prodNum[n] test = result count = 0 while test > 0: test = test // 10 count += 1 if count == 6: sixNum.append(result) if (result // 10 ** 5 % 10) == (result // 10 ** 0 % 10): if (result // 10 ** 4 % 10) == (result // 10 ** 1 % 10): if (result // 10 ** 3 % 10) == (result // 10 ** 2 % 10): palindromeNum.append(result) # all that fit criteria if result > largest: largest = result print("Largest palindromic: %d" % largest) if __name__ == '__main__': palindromeNum = [] prodNum = [] sixNum = [] main() # Dynamic attempt: Technically its possible but very difficult as we need to # consider set points if a for or while is used to do verification # Think on this... # largest = 0 # count = 6 # result = 994009 # for c in range(0, count // 2, 1): # if (result // 10 ** (count - 1 - c) % 10) == (result // 10 ** (c) % 10): # if result > largest: # largest = result # print(result)
true
e604fb50261893929a57a9377d7e7b0e11a9b851
georgeyjm/Sorting-Tests
/sort.py
2,686
4.34375
4
def someSort(array): '''Time Complexity: O(n^2)''' length = len(array) comparisons, accesses = 0,0 for i in range(length): for j in range(i+1,length): comparisons += 1 if array[i] > array[j]: accesses += 1 array[i], array[j] = array[j], array[i] return array, comparisons, accesses def insertionSort(array): '''Time Complexity: O(n^2)''' length = len(array) comparisons, accesses = 0,0 for i in range(length): for j in range(i): comparisons += 1 if array[j] > array[i]: accesses += 1 array.insert(j,array[i]) del array[i+1] return array, comparisons, accesses def selectionSort(array): '''Time Complexity: O(n^2)''' length = len(array) comparisons, accesses = 0,0 for i in range(length-1): min = i for j in range(i+1,length): comparisons += 1 if array[j] < array[min]: accesses += 1 min = j array[i], array[min] = array[min], array[i] return array, comparisons, accesses def bubbleSort(array): '''Time Complexity: O(n^2)''' length = len(array) comparisons, accesses = 0,0 for i in range(length-1): for j in range(length-1,i,-1): comparisons += 1 if array[j] < array[j-1]: accesses += 1 array[j], array[j-1] = array[j-1], array[j] return array, comparisons, accesses def mergeSort(array,comparisons=0,accesses=0): '''Or is it quick sort??''' if len(array) == 1: return array, comparisons, accesses result = [] middle = len(array) // 2 left, comparisons, accesses = mergeSort(array[:middle],comparisons,accesses) right, comparisons, accesses = mergeSort(array[middle:],comparisons,accesses) leftIndex, rightIndex = 0,0 while leftIndex < len(left) and rightIndex < len(right): comparisons += 1 if left[leftIndex] > right[rightIndex]: result.append(right[rightIndex]) rightIndex += 1 else: result.append(left[leftIndex]) leftIndex += 1 result += left[leftIndex:] + right[rightIndex:] return result, comparisons, accesses def bogoSort(array): '''Time Complexity: O(1) (best), O(∞) (worst)''' from random import shuffle comparisons, accesses = 0,0 while True: for i in range(1, len(array)): comparisons += 1 if array[i] < array[i-1]: break else: break shuffle(array) accesses += 1 return array, comparisons, accesses
true
a82eb08a4de5bab1c90099a414eda670219aeb95
eliaskousk/example-code-2e
/21-async/mojifinder/charindex.py
2,445
4.15625
4
#!/usr/bin/env python """ Class ``InvertedIndex`` builds an inverted index mapping each word to the set of Unicode characters which contain that word in their names. Optional arguments to the constructor are ``first`` and ``last+1`` character codes to index, to make testing easier. In the examples below, only the ASCII range was indexed. The `entries` attribute is a `defaultdict` with uppercased single words as keys:: >>> idx = InvertedIndex(32, 128) >>> idx.entries['DOLLAR'] {'$'} >>> sorted(idx.entries['SIGN']) ['#', '$', '%', '+', '<', '=', '>'] >>> idx.entries['A'] & idx.entries['SMALL'] {'a'} >>> idx.entries['BRILLIG'] set() The `.search()` method takes a string, uppercases it, splits it into words, and returns the intersection of the entries for each word:: >>> idx.search('capital a') {'A'} """ import sys import unicodedata from collections import defaultdict from collections.abc import Iterator STOP_CODE: int = sys.maxunicode + 1 Char = str Index = defaultdict[str, set[Char]] def tokenize(text: str) -> Iterator[str]: """return iterator of uppercased words""" for word in text.upper().replace('-', ' ').split(): yield word class InvertedIndex: entries: Index def __init__(self, start: int = 32, stop: int = STOP_CODE): entries: Index = defaultdict(set) for char in (chr(i) for i in range(start, stop)): name = unicodedata.name(char, '') if name: for word in tokenize(name): entries[word].add(char) self.entries = entries def search(self, query: str) -> set[Char]: if words := list(tokenize(query)): found = self.entries[words[0]] return found.intersection(*(self.entries[w] for w in words[1:])) else: return set() def format_results(chars: set[Char]) -> Iterator[str]: for char in sorted(chars): name = unicodedata.name(char) code = ord(char) yield f'U+{code:04X}\t{char}\t{name}' def main(words: list[str]) -> None: if not words: print('Please give one or more words to search.') sys.exit(2) # command line usage error index = InvertedIndex() chars = index.search(' '.join(words)) for line in format_results(chars): print(line) print('─' * 66, f'{len(chars)} found') if __name__ == '__main__': main(sys.argv[1:])
true