blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a6b2127082c3e3eccf8098d8e370d701c5a876db
BlackMetall/trash
/lesson 9 (practice1).py
959
4.1875
4
#Задача 1. Курьер #Вам известен номер квартиры, этажность дома и количество квартир на этаже. #Задача: написать функцию, которая по заданным параметрам напишет вам, #в какой подъезд и на какой этаж подняться, чтобы найти искомую квартиру. room = int(input('Введите номер квартиры ')) # кол-во квартир floor = int(5) # кол-во этажей roomfloor = int(3) # кол-во квартир на этаже c = floor * roomfloor # кол-во квартир в подъезде x = room // c y = (x + 1) # узнаём в каком подъезде квартира z = room % c d = z // roomfloor s = (d + 1) # узнаём на каком этаже print(str(y) + ' Подъезд') print(str(s) + ' Этаж')
false
a40410c97ef48d989ce91b6d23262720f60138dc
rajeshberwal/dsalib
/dsalib/Stack/Stack.py
1,232
4.25
4
class Stack: def __init__(self): self._top = -1 self.stack = [] def __len__(self): return self._top + 1 def is_empty(self): """Returns True is stack is empty otherwise returns False Returns: bool: True if stack is empty otherwise returns False """ return self._top == -1 def push(self, data): """Add data at the end of the stack. Args: data (Any): element that we want to add """ self.stack.append(data) self._top += 1 def pop(self): """Remove the last element from stack and returns it's value. Raises: IndexError: If stack is empty raise an Index error Returns: Any: element that we have removed from stack""" if self.is_empty(): raise IndexError("stack is empty") self._top += 1 return self.stack.pop() def peek(self): """returns the current top element of the stack.""" if self.is_empty(): raise IndexError("stack is empty") return self.stack[self._top] def __str__(self): return ''.join([str(elem) for elem in self.arr])
true
04d70de92bfca1f7b293f344884ec1e23489b7e4
rajeshberwal/dsalib
/dsalib/Sorting/insertion_sort.py
547
4.375
4
def insertion_sort(array: list) -> None: """Sort given list using Merge Sort Technique. Time Complexity: Best Case: O(n), Average Case: O(n ^ 2) Worst Case: O(n ^ 2) Args: array (list): list of elements """ for i in range(1, len(array)): current_num = array[i] for j in range(i - 1, -1, -1): if array[j] > current_num: array[j], array[j + 1] = array[j + 1], array[j] else: array[j + 1] = current_num break
true
6705bd7dfa677bd27dbcf200aaa3f7dc6cd6cb55
laurenc176/PythonCrashCourse
/Lists/simple_lists_cars.py
938
4.5
4
#organizing a list #sorting a list permanently with the sort() method, can never revert #to original order cars = ['bmw','audi','toyota','subaru'] cars.sort() print(cars) #can also do reverse cars.sort(reverse=True) print(cars) # sorted() function sorts a list temporarily cars = ['bmw','audi','toyota','subaru'] print("Here is the orginal list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars) # Can print a list in reverse order using reverse() method, changes it permanently # doesnt sort backward alphabetically, simply reverses order of the list cars = ['bmw','audi','toyota','subaru'] print(cars) cars.reverse() print(cars) #other methods I already know: len(cars) # length of the list cars[-1] # using -1 as an index will always return the last item in a list unless list is empty, then will get an error
true
68654f6011396a2f0337ba2d591a7939d609b3ed
laurenc176/PythonCrashCourse
/Files and Exceptions/exceptions.py
2,711
4.125
4
#Handling exceptions #ZeroDivisionError Exception, use try-except blocks try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") #Using Exceptions to Prevent Crashes print("Give me two numbers, and I'll divide them") print("Enter 'q' to quit.") #This will crash if second number is 0 while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("\nSecond number: ") if second_number == 'q': break answer = int(first_number) / int(second_number) #Prevent crash: while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("\nSecond number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by zero!") else: print(answer) #FileNotFoundError Exception try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"Sorry, the file {filename} does not exist") #Analyzing Text #Many classic lit are available as simple text files because they are in public domain #Texts in this section come from Project Gutenberg(http://gutenberg.org/) title = "Alice in Wonderland" title.split() filename = 'alice.txt' try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"Sorry, the file {filename} does not exist") else: #Count the approx number of words in the file. words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.") #Working with Multiple files, create a function def count_words(filename): """Count the approx number of words in the file.""" try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"Sorry, the file {filename} does not exist") else: words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.") filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename) #Fail silently - you don't need to report every exception #write a block as usual, but tell Python to do nothing in the except block: def count_words(filename): """Count the approx number of words in the file.""" try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: pass #will fail silently, acts as a placeholder else: words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.")
true
fbc01f2c549fae60235064d839c55d98939ae775
martinskillings/tempConverter
/tempConverter.py
2,231
4.3125
4
#Write a program that converts Celsius to Fahrenheit or Kelvin continueLoop = 'f' while continueLoop == 'f': celsius = eval(input("Enter a degree in Celsius: ")) fahrenheit = (9 / 5 * celsius + 32) print(celsius, "Celsius is", format(fahrenheit, ".2f"), "Fahrenheit") #User prompt to switch to different temperature setting or terminate program continueLoop = input("Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: ") if continueLoop == 'k': celsius = eval(input("Enter a degree in Celsius: ")) kelvin = celsius + 273.15 print(celsius, "Celsius is", format(kelvin, ".2f"), "Kelvin") continueLoop = input("Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: ") if continueLoop == 'q': print ("Good-Bye") ''' Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> RESTART: C:/Users/marti/AppData/Local/Programs/Python/Python36-32/tempConverter.py Enter a degree in Celsius: 43 43 Celsius is 109.40 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 43 43 Celsius is 316.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f Enter a degree in Celsius: 0 0 Celsius is 32.00 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 0 0 Celsius is 273.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f Enter a degree in Celsius: 100 100 Celsius is 212.00 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 100 100 Celsius is 373.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f Enter a degree in Celsius: 37 37 Celsius is 98.60 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 37 37 Celsius is 310.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: q Good-Bye >>> '''
true
79723bc580e8f7ccd63a8b86c182c783a56d3329
SuzanneRioue/programmering1python
/Lärobok/kap 8/kap. 8, sid. 103 - list comprehensions.py
1,297
4.34375
4
#!/usr/local/bin/python3.9 # Filnamn: kap. kap. 8, sid. 103 - list comprehensions.py # Kapitel 8 - Listor och tipplar # Programmering 1 med Python - Lärobok # Exempeldata listaEtt = [9, 3, 7] # Med listomfattningar (list comprehensions) menas att man skapar en ny lista # där varje element är resultatet av någon operation på en annan # itererbar variabel eventuella villkor måste också uppfyllas # Här skapar vi en ny lista med uppräkning av t, talen finns ej från början listaTvå = [t for t in range(10)] print(listaTvå) # Skapar en ny lista med utgångspunkt av t i range-inställningarna listaTre = [t for t in range(3, 10, 3)] print('listaTre:', listaTre) # Skapar en ny lista med utgångspunkt av att kvadrera t utifrån # range-inställningarna listaFyra = [t**2 for t in range(3, 10, 3)] print('listaFyra:', listaFyra) # Skapa en ny lista där villkoret att inte ta med tal som är jämt delbara med 5 listaFem = [t for t in range(1, 26) if t % 5 != 0] print('listaFem:', listaFem) # Slå samman listor (konkatenera) listaEtt = listaEtt + listaFyra print('Efter sammanslagning med listaFyra är listaEtt:', listaEtt) # Med metoden append så skapar du en lista i en lista listaEtt.append(listaTre) print('Efter sammanslagning med listaTre är listaEtt:', listaEtt)
false
f38757087bf31b61d8238f3e98798a8799f1b6f8
SuzanneRioue/programmering1python
/Lärobok/kap 8/kap. 8, sid. 104 - sammanfattning med exempel.py
2,712
4.1875
4
#!/usr/local/bin/python3.9 # Filnamn: kap. 8, sid. 104 - sammanfattning med exempel.py # Kapitel 8 - Listor och tipplar # Programmering 1 med Python - Lärobok # Exempeldata lista = [7, 21, 3, 12] listaLäggTill = [35, 42] listaSortera = [6, 2, 9, 1] listaNamn = ['Kalle', 'Ada', 'Pelle', 'Lisa'] # len(x) Ta reda på antal element i en lista samt vilket nr sista index är antalElement = len(lista) sistaIndex = antalElement - 1 print('lista: ', lista, 'består av', antalElement, ' element och sista indexposten är',sistaIndex) # sorted() Skapar en ny lista som är sorterad print('listaSortera:', listaSortera) nySorteradLista = sorted(listaSortera) print('nySorteradLista baserad på en sorterad listaSortera:', nySorteradLista) # sort() returnerar en sorterad lista print('En numrerad lista för sortering:', lista) lista.sort() print('En numrerad lista efter sortering:', lista) print('En alfabetisk lista för sortering:', listaNamn) listaNamn.sort() print('En alfabetisk lista efter sortering:', listaNamn) # append(x) lägg till element i slutet av befintlig lista print('lista före tillägg:', lista) lista.append(28) print('lista efter tillägg:', lista) # extend(lista) sammanfoga/konkatenera två listor, går med + print('lista före sammanfogning:', lista) print('med listaLäggTill:', listaLäggTill) # lista.extend(listaLäggTill) ¤ Krånglig metod lista = lista + listaLäggTill # Bättre och enklare metod print('lista efter sammanfogning:', lista) # insert(x) infoga elemet på indexposition x print('listaNamn före infogandet av ett namn till:', listaNamn) listaNamn.insert(1, 'Agnes') print('listaNamn efter infogandet av ett namn till:', listaNamn) # remove(x) tar bort första elementet i en lista med värdet/strängen x print('listaNamn före borttagande av namnet Kalle:', listaNamn) listaNamn.remove('Kalle') print('listaNamn efter borttagande av namnet Kalle:', listaNamn) # pop(x) ta bort element med index x, utelämnas x tas sista elemnt bort print('lista före borttag av index 0 och sista index:', lista) lista.pop(0) lista.pop() print('lista efter bottag av index 0 och sista index:', lista) # index(x) tar reda på index nummer för element x print('listaNamn:', listaNamn) finnsPåIndex = listaNamn.index('Lisa') print('Lisa finns på indexposition:', finnsPåIndex) # count(x) räkna antal förekomster av element x lista.append(7) # Vi lägger till en 7:a till lista antal7or = lista.count(7) print('lista ser nu ut så här:', lista) print('Det finns', antal7or, 'st 7:or i lista') # reversed() Vänder listan bak och fram print('lista ser nu ut så här:', lista) lista.reverse() print('efter att vi vänt på listan så ser den ut så här:', lista)
false
70a075b1fba763f3a12d1baecbc20c50930c0c3d
SourDumplings/CodeSolutions
/Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/010向列表中添加成绩.py
287
4.21875
4
#向列表中添加成绩 #Coding 酸饺子 print('-------------酸饺子学Python-------------') member = ['小甲鱼', '黑夜', '迷途', '怡静', '秋舞斜阳'] member.insert(1, 88) member.insert(3, 90) member.insert(5, 85) member.insert(7, 90) member.insert(9, 88) print(member)
false
d5a296818f6bd02b8c03c76b2aa042abbcb4ee17
AlexanderOHara/programming
/week03/absolute.py
336
4.15625
4
# Give the absolute value of a number # Author Alexander O'Hara # In the question, number is ambiguous but the output implies we should be # dealing with floats so I am casting the input to a flat number = float (input ("Enter a number: ")) absoluteValue = abs (number) print ('The absolute value of {} is {}'. format (number, absoluteValue))
true
faf268ea926783569bf7e2714589f264ed4f3554
Teddy-Sannan/ICS3U-Unit2-02-Python
/area_and_perimeter_of_circle.py
606
4.1875
4
#!/usr/bin/env python3 # Created by: Teddy Sannan # Created on: September 16 # This program calculates the area and perimeter of a rectangle def main(): # main function print("We will be calculating the area and perimeter of a rectangle") print("") # input length = int(input("Enter the length (mm): ")) width = int(input("Enter the width (mm): ")) # process perimeter = 2 * (length + width) area = length * width print("") # output print("Perimeter is {} mm".format(perimeter)) print("Area is {} mm^2".format(area)) if __name__ == "__main__": main()
true
158450f4cb59c6890e6de4931de18e66a4f5ef48
FraserTooth/python_algorithms
/01_balanced_symbols_stack/stack.py
865
4.21875
4
class Stack: def __init__(self): self.items = [] def push(self, item): """Adds an item to end Returns Nothing Time Complexity = O(1) """ self.items.append(item) def pop(self): """Removes Last Item Returns Item Time Complexity = O(1) """ if self.items: return self.items.pop() return None def peek(self): """Returns Last Item Time Complexity = O(1) """ if self.items: return self.items[-1] return None def size(self): """Returns Size of Stack Time Complexity = O(1) """ return len(self.items) def is_empty(self): """Returns Boolean of whether list is empty Time Complexity = O(1) """ return self.items == []
true
14d98d23d3617c08a2aefd1b4ced2d80c5a9378c
168959/Datacamp_pycham_exercises2
/Creat a list.py
2,149
4.40625
4
# Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Print out second element from areas" print(areas[1]) "# Print out last element from areas" print(areas[9]) "# Print out the area of the living room" print(areas[5]) "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Subset and calculate" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Slicing and dicing" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Use slicing to create downstairs" downstairs = areas[0:6] "# Use slicing to create upstairs" upstairs = areas[6:10] "# Print out downstairs and upstairs" print(downstairs) print(upstairs) "# Alternative slicing to create downstairs" downstairs = areas[:6] "# Alternative slicing to create upstairs" upstairs = areas[-4:] "#Replace list elements" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Correct the bathroom area" areas[-1] = 10.50 # Change "living room" to "chill zone" areas[4] = "chill zone" "#Extend a list" areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50] "# Add poolhouse data to areas, new list is areas_1" areas_1 = areas + ["poolhouse", 24.5] "# Add garage data to areas_1, new list is areas_2" areas_2 = areas_1 + ["garage", 15.45] "#Inner workings of lists" "# Create list areas" areas = [11.25, 18.0, 20.0, 10.75, 9.50] "# Create areas_copy" areas_copy = list(areas) "# Change areas_copy" areas_copy[0] = 5.0 "# Print areas" print(areas)
true
a65aa34ef32d7fced8a91153dae77e48f5cc1176
2019-fall-csc-226/a02-loopy-turtles-loopy-languages-henryjcamacho
/Camachoh- A02.py
1,133
4.15625
4
###################################################################### # Author: Henry Camacho TODO: Change this to your name, if modifying # Username: HenryJCamacho TODO: Change this to your username, if modifying # # Assignment: A02 # Purpose: To draw something we lie with loop ###################################################################### # Acknowledgements: # # original from # # licensed under a Creative Commons # Attribution-Noncommercial-Share Alike 3.0 United States License. ###################################################################### import turtle wn = turtle.Screen() circle = turtle.Turtle() circle.speed(10) circle.fillcolor("yellow") circle.begin_fill() for face in range(75): circle.forward(10) circle.right(5) circle.end_fill() eyes = turtle.Turtle() eyes.speed(10) eyes.penup() eyes.setpos(50, -50) eyes.shape("triangle") eyes.stamp() eyes.setpos (-50, -50) mouth = turtle.Turtle() mouth.speed(10) mouth.penup() mouth.setpos(-50, -100) mouth.pendown() mouth.right(90) for smile in range(30): mouth.forward(5) mouth.left(5) wn.exitonclick()
true
5c703ed90acda4eaba3364b6f510d28622ddc4a0
ndenisj/web-dev-with-python-bootcamp
/Intro/pythonrefresher.py
1,603
4.34375
4
# Variables and Concatenate # greet = "Welcome To Python" # name = "Denison" # age = 6 # coldWeather = False # print("My name is {} am {} years old".format(name, age)) # Concatenate # Comment: codes that are not executed, like a note for the programmer """ Multi line comment in python """ # commentAsString = """ # This is more like # us and you can not do that with me # or i will be mad # """ # print(commentAsString) # If statement # if age > 18: # print("You can VOTE") # elif age < 10: # print("You are a baby") # else: # print("You are too young") # FUNCTIONS # def hello(msg, msg2=""): #print("This is a function - " + msg) # hello("Hey") # hello("Hey 2") # LIST - Order set of things like array # names = ["Dj", "Mike", "Paul"] # names.insert(1, "Jay") # # print(names[3]) # # del(names[3]) # # print(len(names)) # length # names[1] = "Peter" # print(names) # LOOPS # names = ["Dj", "Mike", "Paul"] # for name in names: # #print(name) # for x in range(len(names)): # print(names[x]) # for x in range(0, 5): # print(x) # age = 2 # while age < 3: # print(age) # age += 1 # DICTIONARY # allnames = {'Paul': 23, 'Patrick': 32, 'Sally': 12} # print(allnames) # print(allnames['Sally']) # CLASSES # class Dog: # dogInfo = 'Dogs are cool' # # Constructor of the class # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print('Bark - ' + self.dogInfo) # myDog = Dog("Denis", 33) # create an instance or object of the Dog Class # myDog.bark() # print(myDog.age)
true
1c32272ef45f6e6958cee58d95088c5b475269b1
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Tuplas.py
808
4.28125
4
# La tupla luego de ser inicializada no se puede modificar frutas = ("Naranja", "Platano", "Guayaba") print(frutas) print(len(frutas)) print(frutas[0]) # Acceder a un elemento print(frutas[-1]) # Navegación inversa #Tambien funcionan los rangos igual que en las listas print(frutas[0:2]) # Una Lista se puede inicializar con una tubpla frutasLista = list(frutas) frutasLista[1] = "Platanito" # Una tupla se puede modificar, metiendo una lista que sustituye su valor frutas = tuple(frutasLista) # Iterar sobre la tupla, esto se realiza de igual manera que con las listas for fruta in frutas: print(fruta, end=" ") #El end=" " indica como queremos que finalize el imprimir fruta #Tarea tupla = (13, 1, 8, 3, 2, 5, 8) lista = [] for t in tupla: if t < 5: lista.append(t) print(lista)
false
57bade1fd06c0bf6e9814bea60b5e4e6a8d35163
suyash248/ds_algo
/Queues/queueUsingStack.py
1,364
4.15625
4
class QueueUsingStack(object): __st1__ = list() __st2__ = list() def enqueue(self, elt): self.__st1__.append(elt) def dequeue(self): if self.empty(): raise RuntimeError("Queue is empty") if len(self.__st2__) == 0: while len(self.__st1__) > 0: self.__st2__.append(self.__st1__.pop()) return self.__st2__.pop() def size(self): return len(self.__st1__) + len(self.__st2__) def empty(self): return len(self.__st1__) == 0 and len(self.__st2__) == 0 if __name__ == '__main__': q = QueueUsingStack() choices = "1. Enqueue\n2. Dequeue\n3. Size\n4. Is Empty?\n5. Exit" while True: print choices choice = input("Enter your choice - ") if choice == 1: elt = raw_input("Enter element to be enqueued - ") q.enqueue(elt) elif choice == 2: try: elt = q.dequeue() print "Dequeued:", elt except Exception as e: print "Error occurred, queue is empty?", q.empty() elif choice == 3: print "Size of queue is", q.size() elif choice == 4: print "Queue is", "empty" if q.empty() else "not empty." elif choice == 5: break else: print "Invalid choice"
false
61e6633eeadf4384a18603640e30e0fa0a6998c8
suyash248/ds_algo
/Array/stockSpanProblem.py
959
4.28125
4
from Array import empty_1d_array # References - https://www.geeksforgeeks.org/the-stock-span-problem/ def stock_span(prices): # Stores index of closest greater element/price. stack = [0] spans = empty_1d_array(len(prices)) # Stores the span values, first value(left-most) is 1 as there is no previous greater element(price) available. spans[0] = 1 # When we go from day i-1 to i, we pop the days when the price of the stock was less than or equal to price[i] and # then push the value of day i back into the stack. for i in range(1, len(prices)): cur_price = prices[i] while len(stack) != 0 and prices[stack[-1]] <= cur_price: stack.pop() spans[i] = (i+1) if len(stack) == 0 else (i-stack[-1]) stack.append(i) return spans if __name__ == '__main__': prices = [10, 4, 5, 90, 120, 80] spans = stock_span(prices) print("Prices:", prices) print("Spans:", spans)
true
d21394227d4390b898fc1588593e43616ed7e502
suyash248/ds_algo
/Misc/sliding_window/substrings_with_distinct_elt.py
2,324
4.125
4
''' Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1 Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters. ''' def __num_substrings_brute_force__(s: str) -> int: k = 3 res = 0 substr = dict() for i in range(min(k, len(s))): substr[s[i]] = substr.get(s[i], 0) + 1 if len(substr) == k: res += 1 for i in range(0, len(s) - k): left_elt = s[i] right_elt = s[i + k] substr[right_elt] = substr.get(right_elt, 0) + 1 if substr.get(left_elt) > 0: substr[left_elt] -= 1 else: substr.pop(left_elt) if len(substr) == k: res += 1 return res def num_substrings_brute_force(s: str) -> int: res = 0 for i in range(len(s)): res += __num_substrings_brute_force__(s[i:]) return res ############################################################################### def num_substrings_sliding_window(s: str) -> int: left = 0 right = 0 end = len(s) - 1 hm = dict() count = 0 while right != len(s): hm[s[right]] = hm.get(s[right], 0) + 1 while hm.get('a', 0) > 0 and hm.get('b', 0) > 0 and hm.get('c', 0) > 0: count += 1 + (end - right) hm[s[left]] -= 1 left += 1 right += 1 return count if __name__ == '__main__': s = "abcabc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "aaacb" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "abc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res)
true
80ebbfd1da7c991ac5810797b90fe493ec22b654
shangkh/github_python_interview_question
/11.简述面向对象中__new__和__init__区别.py
1,384
4.21875
4
""" __init__ 是初始化方法,创建对象后,就立刻被默认调用了,可以接收参数 """ """ __new__ 1.__new__ 至少要有一个参数 cls,代表当前类,此参数在实例化时由python解释器自动识别 2.__new__ 必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意, 可以return父类(通过super(当前类名, cls))__new__出来的实例, 或者直接是object的__new__出来的实例 3.__int__有一个参数self,就是这个__new__返回的实例, __init__在__new__的基础上可以完成一些其他的初始化动作, __init__不需要返回值 4.如果__new__创建的是当前类的实例,会自动调用__init__函数, 通过return语句里面调用的__new__函数的 第一个参数是cls来保证是当前类实例,如果是其他类的类名; 那么实际创建返回的就是其他类的实例, 其实就不会调用当前类的__init__函数,也不会调用其他类的__init__函数 """ class A(object): def __int__(self): print("这是__init__方法", self) def __new__(cls, *args, **kwargs): print("这是cls的ID:", id(cls)) print("这是__new__方法", object.__new__(cls)) return object.__new__(cls) if __name__ == '__main__': A() print("这是类A的ID:", id(A))
false
12562fa1658d275e15075f71cff3fac681c119ab
green-fox-academy/Angela93-Shi
/week-01/day-4/data_structures/data_structures/product_database.py
715
4.34375
4
map={'Eggs':200,'Milk':200,'Fish':400,'Apples':150,'Bread':50,'Chicken':550} # Create an application which solves the following problems. # How much is the fish? print(map['Fish']) # What is the most expensive product? print(max(map,key=map.get)) # What is the average price? total=0 for key in map: total=total+map[key] average=total/len(map) print(average) # How many products' price is below 300? n=0 for key in map: if map[key] < 300: n+=1 print(n) # Is there anything we can buy for exactly 125? for key,value in map.items(): if map[key] == 125: print("yes") else: print("No") break # What is the cheapest product? print(min(map,key=map.get))
true
587a7726500b091aea4511e4036f8750c229ecaa
green-fox-academy/Angela93-Shi
/week-05/day-01/all_positive.py
319
4.3125
4
# Given a list with the following items: 1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14 # Determine whether every number is positive or not using all(). original_list=[1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14] def positive_num(nums): return all([num > 0 for num in nums]) print(positive_num(original_list))
true
8fcf16851182307c41d9c5dd77e8d42b783628c7
green-fox-academy/Angela93-Shi
/week-01/day-4/function/factorial.py
409
4.375
4
# - Create a function called `factorio` # that returns it's input's factorial num = int(input("Please input one number: ")) def factorial(num): factorial=1 for i in range(1,num + 1): factorial = factorial*i print("%d 's factorial is %d" %(num,factorial)) if num < 0: print("抱歉,负数没有阶乘") elif num == 0: print("0 的阶乘为 1") else: factorial(num)
true
c5d9cfe8cdda4d4fdc98f77221c15bb23da5e100
green-fox-academy/Angela93-Shi
/week-01/day-4/data_structures/data_structures/telephone_book.py
478
4.1875
4
#Create a map with the following key-value pairs. map={'William A. Lathan':'405-709-1865','John K. Miller':'402-247-8568','Hortensia E. Foster':'606-481-6467','Amanda D. Newland‬':'319-243-5613','Brooke P. Askew':'307-687-2982'} print(map['John K. Miller']) #Whose phone number is 307-687-2982? for key,value in map.items(): if value == '307-687-2982': print(key) #Do we know Chris E. Myers' phone number? for key,value in map.items(): if key == 'Chris E. Myers': print('Yes') else: print('No') break
false
c60df7c6d2aa3eaecdc1c95bc7bba9a96eff1add
kasemodz/RaspberryPiClass1
/LED_on_off.py
831
4.125
4
# The purpose of this code is to turn the led off and on. # The LED is connected to GPIO pin 25 via a 220 ohm resistor. # See Readme file for necessary components #! /usr/bin/python #We are importing the sleep from the time module. from time import sleep #We are importing GPIO subclass from the class RPi. We are referring to this subclass via GPIO. import RPi.GPIO as GPIO # Resets all pins to factory settings GPIO.cleanup() # Sets the mode to pins referred by "GPIO__" pins (i.e. GPIO24) GPIO.setmode(GPIO.BCM) # Configures GPIO Pin 25 as an output, because we want to # control the state of the LED with this code. GPIO.setup(25, GPIO.OUT) # Turns the LED state to ON by the HIGH command. To turn off the LED, change HIGH to LOW, # then run this file again. ie. GPIO.output(25, GPIO.LOW) GPIO.output(25, GPIO.HIGH)
true
99f64a174783c4a4f8a4a304672a096b0fe04ccc
Poter0222/poter
/PYTHON/03.04/string.py
697
4.1875
4
#coding=UTF-8 # 03 # 字串運算 # 字串會對內部的字元編號(索引),從 0 開始 s="hello\"o" # \ 在雙引號前面打入,代表跳脫(跟外面雙引號作區隔) 去避免你打的字串中有跟外面符號衝突的問題 print(s) # 字串的串接 s="hello"+"world" print(s) s="hello" "world" # 同 x="hello"+"world" print(s) # 字串換行 s="hello\nworld" # /n代表換行 print(s) s=""" hello world""" # 前後加入“”“可將字串具體空出你空的行數 print(s) s="hello"*3+"world" #概念同 先乘除後加減 print(s) # 對字串編號 s="hello" print(s[1]) print(s[1:4]) # 不包含第 4 個字元 print(s[:4]) # 到第 4 個字串(不包含)
false
e799fbff3d6be502d48b68fb1094b6dd4bcc4079
yihangx/Heart_Rate_Sentinel_Server
/validate_heart_rate.py
901
4.25
4
def validate_heart_rate(age, heart_rate): """ Validate the average of heart rate, and return the patient's status. Args: age(int): patient'age heart_rate(int): measured heart rates Returns: status(string): average heart rate """ status = "" if age < 1: tachycardia_threshold = -1 if age in range(1, 3): tachycardia_threshold = 151 if age in range(3, 5): tachycardia_threshold = 137 if age in range(5, 8): tachycardia_threshold = 133 if age in range(8, 12): tachycardia_threshold = 130 if age in range(12, 16): tachycardia_threshold = 119 if age > 15: tachycardia_threshold = 100 if tachycardia_threshold != -1: if heart_rate >= tachycardia_threshold: status = "tachycardia" else: status = "not tachycardia" return status
true
43382e8fe8fac375b8bdbbda97a67d853a5a7e19
eleanorpark/Python-Dec-2018-CrashCourse
/areaofcircle.py
348
4.125
4
def area_of_circle(radius): 3.14*radius*radius radius=2 area = 3.14*radius*radius area_of_circle(radius) print('area of circle of radius {} is:{}'.format(radius,area)) def area_of_circle(radius): 3.14*radius*radius radius=10 area = 3.14*radius*radius area_of_circle(radius) print('area of circle of radius {} is:{}'.format(radius,area))
false
0f7cfefeb124d76ef25dc904500246c9e843658d
xg04tx/number_game2
/guessing_game.py
2,282
4.125
4
def main(): while True: try: num = int( input("Please, think of a number between 1 and 1000. I am about to try to guess it in 10 tries: ")) if num < 1 or num > 1000: print("Must be in range [1, 100]") else: computer_guess(num) except ValueError: print("Please put in only whole numbers for example 4") def computer_guess(num): NumOfTry = 10 LimitLow = 1 LimitHigh = 1000 NumToGuess = 500 while NumOfTry != 0: try: print("I try: ", NumToGuess) print("Please type: 1 for my try is too high") print(" 2 for my try is too low") print(" 3 I guessed your number") Answer = int(input("So did I guess right?")) if 1 < Answer > 3: print("Please enter a valid answer. 1, 2 and 3 are the valid choice") NumOfTry = NumOfTry + 1 if Answer == 1: LimitHigh = NumToGuess print("Hmm, so your number is between ", LimitLow, "and ", LimitHigh) NumOfTry = NumOfTry - 1 print(NumOfTry, "attempts left") NumToGuess = int(((LimitHigh - LimitLow) / 2) + LimitLow) if NumToGuess <= LimitLow: NumToGuess = NumToGuess + 1 if LimitHigh - LimitLow == 2: NumToGuess = LimitLow + 1 elif Answer == 2: LimitLow = NumToGuess print("Hmm, so your number is between ", LimitLow, "and ", LimitHigh) NumOfTry = NumOfTry - 1 print(NumOfTry, "attempts left") NumToGuess = int(((LimitHigh - LimitLow) / 2) + LimitLow) if NumToGuess <= LimitLow: NumToGuess = NumToGuess + 1 if LimitHigh - LimitLow == 2: NumToGuess = LimitLow + 1 elif num == NumToGuess: print("Don't cheat") NumOfTry = NumOfTry + 1 elif Answer == 3: print("I won!!!!") NumOfTry = 0 except: return main() if __name__ == '__main__': main()
true
4deedfe0dea559088f4d2652dfe71479fce81762
saman-rahbar/in_depth_programming_definitions
/errorhandling.py
965
4.15625
4
# error handling is really important in coding. # we have syntax error and exceptions # syntax error happens due to the typos, etc. and usually programming languages can help alot with those # exceptions, however, is harder to figure and more fatal. So in order to have a robust code you should # handle the errors and take care of the exceptions, and raise exceptions when necessary. """ Circuit failure example """ class Circuit: def __init__(self, max_amp): self.capacity = max_amp # max capacity in amps self.load = 0 # current load def connect(self, amps): """ function to check the connectivity :param amps: int :return: None """ if self.capacity += amps > max_amp: raise exceptions("Exceeding max amps!") elif self.capacity += amps < 0: raise exceptions("Capacity can't be negative") else: self.capacity += amps
true
0a8a9a0a4c6ca24fde6c09886c52d1d5c7817a24
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex40b.py
974
4.53125
5
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." # ok pay attention! cities ['_find'] = find_city while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break #this line is the msot important ever! study! city_found = cities['_find'] (cities, state) print city_found """ 'CA' = key More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Continue with these: http://docs.python.org/2/tutorial/datastructures.html http://docs.python.org/2/library/stdtypes.html - mapping types """
true
5892f0c1c6cb36853a85e541cb6b3259346546e9
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex06.py
898
4.1875
4
# Feed data directly into the formatting, without variable. x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" #Referenced and formatted variables, within a variable. y = "Those who know %s and those who %s." % (binary, do_not) print x print y #r puts quotes around string print "I said: %r." % x #s does not put quotes around string, so they are added manually print "I also said: '%s'." % y hilarious = False #variable anticipates formatting of yet unkown variable joke_evaluation = "Isn't that joke so funny?! %r" #joke_evaluation has formatting delclared in variable, when called formatting statement is completed by closing the formatting syntax print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." #since variables are strings python concatenates, rather than perform mathmetic equation with error print w + e
true
59c54a778af80dc495ed27f83006893f36e9a9e7
saurabhslsu560/myrespository
/oop3.py
1,028
4.15625
4
class bank: bank_name="union bank of india" def __init__(self,bank_bal,acc_no,name): self.bank_bal=bank_bal self.acc_no=acc_no self.name=name return def display(self): print("bank name is :",bank.bank_name) print("account holder name is:",self.name) print("account number is :",self.acc_no) print("account balance is :",self.bank_bal) return def main(): print("enter first customer detail:") k=input("enter name:") l=int(input("enter account number:")) m=int(input("enter balance:")) print("enter second customer detail:") n=input("enter name:") o=int(input("enter account number:")) p=int(input("enter balance:")) print("first customer detail is:") obj=bank(m,l,k) obj.display() print("second customer detail is:") obj=bank(p,o,n) obj.display() return bank.main()
false
71a2fe42585b7a6a2fece70674628c1b529f3371
pltuan/Python_examples
/list.py
545
4.125
4
db = [1,3,3.4,5.678,34,78.0009] print("The List in Python") print(db[0]) db[0] = db[0] + db[1] print(db[0]) print("Add in the list") db.append(111) print(db) print("Remove in the list") db.remove(3) print(db) print("Sort in the list") db.sort() print(db) db.reverse() print(db) print("Len in the list") print(len(db)) print("For loop in the list") for n_db in db: print(n_db) print(min(db)) print(max(db)) print(sum(db)) my_food = ['rice', 'fish', 'meat'] friend_food = my_food friend_food.append('ice cream') print(my_food) print(friend_food)
true
97745f9a33b8e5653d050d3a5c875c57bc4e5780
WangMingJue/StudyPython
/Test/Python 100 example/Python 练习实例6.py
1,134
4.25
4
# 题目:斐波那契数列。 # # 程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。 # # 在数学上,费波那契数列是以递归的方法来定义: # F0 = 0 (n=0) # F1 = 1 (n=1) # Fn = F[n-1]+ F[n-2](n=>2) # 普通方法 def method_1(index): a, b = 1, 1 for i in range(index - 1): a, b = b, a + b return a # 使用递归 def method_2(index): if index == 1 or index == 2: return 1 return method_2(index - 1) + method_2(index - 2) # 输出前 n 个斐波那契数列 def fib(n): if n == 1: return [1] if n == 2: return [1, 1] fibs = [1, 1] for i in range(2, n): fibs.append(fibs[-1] + fibs[-2]) return fibs if __name__ == '__main__': print("第一种方法输出了第10个斐波那契数列,结果为:{}".format(method_1(10))) print("第二种方法输出了第10个斐波那契数列,结果为:{}".format(method_1(10))) print("输出前10个斐波那契数列,结果为:{}".format(fib(10)))
false
74bda556d528a9346da3bdd6ca7ac4e6bcac6654
adaoraa/PythonAssignment1
/Reverse_Word_Order.py
444
4.4375
4
# Write a program (using functions!) that asks the user for a long string containing multiple words. # Print back to the user the same string, except with the words in backwards order. user_strings = input('input a string of words: ') # prompts user to input string user_set = user_strings.split() # converts string to list print(user_set) backwards_list = user_set[::-1] # makes user_set list print backwards print(backwards_list)
true
7b35393252d51e721ffddde3007105546240e5df
adaoraa/PythonAssignment1
/List_Overlap.py
1,360
4.3125
4
import random # Take two lists, say for example these two:... # and write a program that returns a list that # contains only the elements that are common between # the lists (without duplicates). Make sure your program # works on two lists of different sizes. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] common_list=list(set(a).intersection(b)) # intersection: finds commonalities print(common_list) num1=int(input('How many numbers do you want list1 to have? ' 'enter a number between 5 and 12: ')) num2=int(input('How many numbers do you want list2 to have? ' 'enter a number between 5 and 12: ')) range_list1= int(input('Starting at 1, at what integer do ' 'you want your list to end?: ')) range_list2= int(input('Starting at 1, at what integer do ' 'you want your list to end?: ')) x=random.sample(range(range_list1),num1) y=random.sample(range(range_list2),num2) print(x) print(y) common_elements=list(set(x).intersection(y)) print(common_elements) # variable x generates random list given range the user inputs # variable y does the same as variable x # The varaible common_elements prints the common elements between the random lists # Sometimes there will be no common elements which is why this is impractical
true
7036212232a843fe184358c1b41e5e9cb096d31d
andrew5205/MIT6-006
/ch2/binary_search_tree.py
1,377
4.21875
4
class Node: # define node init def __init__(self, data): self.left = None self.right = None self.data = data # insert into tree def insert(self, data): # if provide data exist if self.data: # 1 check to left child # compare with parent node if data < self.data: # 1.1 if left child not yet exist if self.left is None: self.left = Node(data) # 1.2 if left child exist, insert to the next level(child) else: self.left.insert(data) # 2 check to right child # compare with parent node elif data > self.data: # 2.1 if right child not yet exist if self.right is None: self.right = Node(data) # 2.2 if right child exist, insert to the next level(child) else: self.right.insert(data) else: self.data = data # print func def print_tree(self): if self.left: self.left.print_tree() print(self.data), if self.right: self.right.print_tree() root = Node(12) root.insert(6) root.insert(14) root.insert(3) root.print_tree()
true
8eb212398880ce375cf3541eac5fcd73c1ab95fe
Srbigotes33y/Programacion
/Python/Aprendizaje/Condiociones anidadas/Taller Condiciones2/Ejercicio_5.py
1,767
4.125
4
# Programa que solicita 3 números,los muestra en pantalla de mayor a menor en lineas distintas. # En caso de haber numeros iguales, se pintan en la misma linea. # Solicitud de datos n1=int(input("Ingrese tres números.\nNúmero #1: ")) n2=int(input("Número #2: ")) n3=int(input("Número #3: ")) # En caso de que no se presenten números iguales if n1>n2 and n2>n3: print("\nEl orden de los números es:\n",n1,"\n",n2,"\n",n3,"\n") elif n1>n3 and n3>n2: print("\nEl orden de los números es:\n",n1,"\n",n3,"\n",n2,"\n") elif n2>n3 and n3>n1: print("\nEl orden de los números es:\n",n2,"\n",n3,"\n",n1,"\n") elif n2>n1 and n1>n3: print("\nEl orden de los números es:\n",n2,"\n",n1,"\n",n3,"\n") elif n3>n2 and n2>n1: print("\nEl orden de los números es:\n",n3,"\n",n2,"\n",n1,"\n") elif n3>n1 and n1>n2: print("\nEl orden de los números es:\n",n3,"\n",n1,"\n",n2,"\n") # En caso de que se pressenten números iguales elif n1==n2 and n3<n1: print("\nEl orden de los números es:\n",n1,"=",n2,"\n",n3,"\n") elif n1==n2 and n3>n1: print("\nEl orden de los números es:\n",n3,"\n",n1,"=",n2,"\n") elif n1==n3 and n2<n1: print("\nEl orden de los números es:\n",n3,"=",n1,"\n",n2,"\n") elif n1==n3 and n2>n1: print("\nEl orden de los números es:\n",n2,"\n",n1,"=",n3,"\n") elif n2==n3 and n1<n2: print("\nEl orden de los números es:\n",n2,"=",n3,"\n",n1,"\n") elif n1==n2 and n1>n2: print("\nEl orden de los números es:\n",n1,"\n",n2,"=",n3,"\n") # En caso de que los 3 números sean iguales elif n1==n2 and n2==n3: print("\nLos tres números son iguales\n") # Créditos print("====================================") print("Programa hecho por Alejandro Giraldo") print("====================================\n")
false
25b2d05140a1397680d93d95c6a305f6c39f5602
Srbigotes33y/Programacion
/Python/Aprendizaje/Condiociones anidadas/Taller Condiciones2/Ejercicio_4.py
1,043
4.15625
4
# Programa que pide 3 números y los muestra en pantalla de menor a mayor # Solicitud de datos n1=int(input("Ingrese tres números.\nNúmero #1: ")) n2=int(input("Número #2: ")) n3=int(input("Número #3: ")) # Determinacion y exposición de los resultados if n1>n2 and n2>n3: print("\nEl orden de los números es:\n",n3,"\n",n2,"\n",n1,"\n") elif n1>n3 and n3>n2: print("\nEl orden de los números es:\n",n2,"\n",n3,"\n",n1,"\n") elif n2>n3 and n3>n1: print("\nEl orden de los números es:\n",n1,"\n",n3,"\n",n2,"\n") elif n2>n1 and n1>n3: print("\nEl orden de los números es:\n",n3,"\n",n1,"\n",n2,"\n") elif n3>n2 and n2>n1: print("\nEl orden de los números es:\n",n1,"\n",n2,"\n",n3,"\n") elif n3>n1 and n1>n2: print("\nEl orden de los números es:\n",n2,"\n",n1,"\n",n3,"\n") elif n1==n2 or n1==n3 or n2==n3: print("\nDos o más números son iguales","\n") # Créditos print("====================================") print("Programa hecho por Alejandro Giraldo") print("====================================\n")
false
e9aa4621abbe5b8b60fa7bc02b3a54ba2f42531a
sharmar0790/python-samples
/misc/findUpperLowerCaseLetter.py
241
4.25
4
#find the number of upper and lower case characters str = "Hello World!!" l = 0 u=0 for i in str: if i.islower(): l+=1 elif i.isupper(): u+=1 else: print("ignore") print("Lower = %d, upper = %d" %(l,u))
true
4b6bf4b0865f101b5545c7cb1033c5738c33dc3b
sharmar0790/python-samples
/misc/factors.py
267
4.28125
4
nbr = int(input("Enter the number to find the factors : ")) for i in range(1, nbr+ 1 ): if (nbr % i == 0): if i % 2 == 0: print("Factor is :", i , " and it is : Even") else: print("Factor is :", i , " and it is : Odd")
false
ece16e9a25e880eaa3381b787b12cecf86625886
x223/cs11-student-work-Aileen-Lopez
/March21DoNow.py
462
4.46875
4
import random random.randint(0, 8) random.randint(0, 8) print(random.randint(0, 3)) print(random.randint(0, 3)) print(random.randint(0, 3)) # What Randint does is it accepts two numbers, a lowest and a highest number. # The values of 0 and 3 gives us the number 0, 3, and 0. # I Changed the numbers to (0,8) and the results where 1 0 1. # The difference between Randint and print is that print will continue giving a 3, while Randint stays the same of changes.
true
016c7e2da4516be168d3f51b34888d12e0be1c5d
adrian-calugaru/fullonpython
/sets.py
977
4.4375
4
""" Details: Whats your favorite song? Think of all the attributes that you could use to describe that song. That is: all of it's details or "meta-data". These are attributes like "Artist", "Year Released", "Genre", "Duration", etc. Think of as many different characteristics as you can. In your text editor, create an empty file and name it main.py Now, within that file, list all of the attributes of the song, one after another, by creating variables for each attribute, and giving each variable a value. Here's an example: Genre = "Jazz" Give each variable its own line. Then, after you have listed the variables, print each one of them out. For example: Artist = "Dave Brubeck" Genre = "Jazz" DurationInSeconds = 328 print(Artist) print(Genre) print(DurationInSeconds) Your actual assignment should be significantly longer than the example above. Think of as many characteristics of the song as you can. Try to use Strings, Integers and Decimals (floats)! """
true
4da4b5e0a87f9220caa5fb470cac464fe17975cb
aniketpatil03/Hangman-Game
/main.py
1,650
4.125
4
import random stages = [''' +---+ | | O | /|\ | / \ | Death| ========= ''', ''' +---+ | | O | /|\ | / | | ========= ''', ''' +---+ | | O | /|\ | | | ========= ''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | | | | | ========= ''', ''' +---+ | | O | | | | ========= ''', ''' +---+ | | | | | | ========= '''] # Variable that is going to keep a track of lives lives = 6 # Generating random word from list word_list = ["aardvark", "baboon", "camel"] chosen_word = random.choice(word_list) print("psst, the chosen random word", chosen_word) # Generating as many blanks as the word display = [] for _ in range(len(chosen_word)): display += "_" print(display) game_over = False while not game_over: # Condition for while loop to keep going # Taking input guess from user guess = input("Enter your guess: ").lower() # Replacing the blank value with guessed letter for position in range(len(chosen_word)): letter = chosen_word[position] if letter == guess: display[position] = letter print(display) if guess not in chosen_word: lives = lives - 1 if lives == 0: print("The end, you lose") game_over = True if "_" not in display: game_over = True # Condition which is required to end while loop or goes infinite print("Game Over, you won") # prints stages as per lives left from ASCII Art and art is arranged acc to it print(stages[lives])
false
4ce5c10eaf4a27ff54a1b12c87110659daf3f04a
aubreystevens/image_processing_pipeline
/text_files/Test.py
1,033
4.15625
4
#B.1 def complement(sequence): """This function returns the complement of a DNA sequence. The argument, 'sequence' represents a DNA sequence.""" for base in 'sequence': if 'A' in 'sequence': return 'T' elif 'G' in 'sequence': return 'C' elif 'T' in 'sequence': return 'A' else: return 'G' #B.2 def list_complement(dna): """This function returns the complement of a DNA sequence.""" if 'A': return 'T' elif 'G': return 'C' elif 'T': return 'A' else: return 'G' #B.3 def product(numbers): """Returns sum of all numbers in the list.""" for x in numbers: final += x return final #B.4 def factorial(x): """Returns factorial of number x.""" if x = 0 : return 1 else: return x = x * (x-1) #B.5
true
33d73944bf28351346ac72cbee3f910bcf922911
maneeshapaladugu/Learning-Python
/Practice/Armstrong_Number.py
763
4.46875
4
#Python program to check if a number is Armstrong or not #If the given number is 153, and 1^3 + 5 ^ 3 + 3 ^ 3 == 153, then 153 is an Armstrong number def countDigits(num): result = 0 while num > 0: result += 1 num //= 10 print(result) return result def isArmstrong(num): digitCount = countDigits(num) temp = num result = 0 while temp: result += pow(temp%10, digitCount) temp //= 10 if result == num: return 1 else: return 0 num = int(input("Enter a number:\n")) #Receive the input as an integer if isArmstrong(num): print("%d is an Armstrong Number" %(num)) else: print("%d is not an Armstrong number" %(num))
true
37bd1683785377afe49b17d3aec9700665e3d3db
MyoMinHtwe/Programming_2_practicals
/Practical 5/Extension_3.py
1,804
4.1875
4
def bill_estimator(): MENU = """11 - TARIFF_11 = 0.244618 31 - TARIFF_31 = 0.136928 41 - TARIFF_41 = 0.156885 51 - TARIFF_51 = 0.244567 61 - TARIFF_61 = 0.304050 """ print(MENU) tariff_cost = {11: 0.244618, 31: 0.136928, 41: 0.156885, 51: 0.244567, 61: 0.304050} choice = int(input("Which tariff? 11 or 31 or 41 or 51 or 61: ")) if choice == 11: daily_use = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) bill = (tariff_cost[11] * daily_use * billing_days) print("Estimated bill:$ {:.2f}".format(bill)) elif choice==31: daily_use = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) bill = (tariff_cost[31] * daily_use * billing_days) print("Estimated bill:$ {:.2f}".format(bill)) elif choice==41: daily_use = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) bill = (tariff_cost[41] * daily_use * billing_days) print("Estimated bill:$ {:.2f}".format(bill)) elif choice==51: daily_use = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) bill = (tariff_cost[51] * daily_use * billing_days) print("Estimated bill:$ {:.2f}".format(bill)) elif choice==61: daily_use = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) bill = (tariff_cost[61] * daily_use * billing_days) print("Estimated bill:$ {:.2f}".format(bill)) else: while 1: print("Invalid input") bill_estimator() break bill_estimator()
false
8071c3f0f77261cb68e0c36d09a814ba95fdb474
MyoMinHtwe/Programming_2_practicals
/Practical 5/Extension_1.py
248
4.3125
4
name_to_dob = {} for i in range(2): key = input("Enter name: ") value = input("Enter date of birth (dd/mm/yyyy): ") name_to_dob[key] = value for key, value in name_to_dob.items(): print("{} date of birth is {:10}".format(key,value))
true
cb0c2a4c02c8fee656a94fe659ac0c25115bd4bc
MyoMinHtwe/Programming_2_practicals
/Practical 3/temperatures.py
1,045
4.125
4
MENU = """C - Convert Celsius to Fahreneit F - Convert Fahrenheit to Celsius Q - Quit""" print(MENU) choice = input("Input your choice: ").lower() def main(choice): #choice = input("Input your choice: ").lower() print(choice) i = True while i==True: if choice == "c": celsius = float(input("Celsius: ")) result = calc_celsius(celsius) print("Result: {:.2f} Fahrenheit".format(result)) i = False elif choice == "f": fahrenheit = float(input("Fahrenheit: ")) result = calc_fahrenheit(fahrenheit) print("Result: {:.2f} Celsius".format(result)) i = False elif choice == "q": i = False else: print("Invalid entry: ") choice = input("Input your choice: ") print("Thank you") def calc_celsius(celsius): result = celsius * 9.0 / 5 + 32 return result def calc_fahrenheit(fahrenheit): result = 5 / 9 * (fahrenheit - 32) return result main(choice)
false
a288abbab98175fb70e1c1a34c5c6f4eeeed438a
HarshKapadia2/python_sandbox
/python_sandbox_finished_(by_harsh_kapadia)/tuples_sets.py
1,269
4.25
4
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # create tuple fruit_1 = ('mango', 'watermelon', 'strawberry', 'orange', 'dragon fruit') # using constructor fruit_2 = tuple(('mango', 'watermelon', 'strawberry', 'orange', 'dragon fruit')) print(fruit_1, fruit_2) fruit_3 = ('apple') print(fruit_3, type(fruit_3)) # type str fruit_4 = ('blueberry',) # single value needs trailing comma to be a tuple print(fruit_4, type(fruit_4)) # type tuple # get value print(fruit_1[0]) # values cannot be changed in tuples # fruit_1[0] = 'water apple' # error # deleting a tuple del fruit_2 # print(fruit_2) # o/p: error. 'fruit_2' not defined # length of tuple print(len(fruit_1)) # A Set is a collection which is unordered and unindexed. No duplicate members. fruit_5 = {'mango', 'apple'} # check if in set print('mango' in fruit_5) # RT: bool # add to set fruit_5.add('watermelon') print(fruit_5) # add duplicte member fruit_5.add('watermelon') # doesn't give err, but doesn't insert the duplicate val print(fruit_5) # remove from set fruit_5.remove('watermelon') print(fruit_5) # clear the set (remove all elements) fruit_5.clear() print(fruit_5) # delete set del fruit_5 # print(fruit_5) # o/p: error. 'fruit_5' not defined
true
828e176b7aae604d3f4d38a206d4f1cfa5d49197
HarshKapadia2/python_sandbox
/python_sandbox_finished_(by_harsh_kapadia)/loops.py
854
4.1875
4
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). people = ['Selena', 'Lucas', 'Felix', 'Brad'] # for person in people: # print(person) # break # for person in people: # if person == 'Felix': # break # print(person) # continue # for person in people: # if person == 'Felix': # continue # print(person) # range # for i in range(len(people)): # print(i) # print(people[i]) # for i in range(0, 5): # 0 is included, but 5 is not # print(i) # for i in range(6): # starts from 0, goes till 5 # print(i) # While loops execute a set of statements as long as a condition is true. count = 10 while count > 0: print(count) count -= 1 # count-- does not exist in python (ie, post/pre increment ops do not exist in python)
true
622589e96be15dc7e742ce2a1dc83ea91507b5dc
DeepanshuSarawagi/python
/ModulesAndFunctions/dateAndTime/datecalc.py
354
4.25
4
import time print(time.gmtime(0)) # This will print the epoch time of this system which is usually January 1, 1970 print(time.localtime()) # This will print the local time print(time.time()) # This will print the time in seconds since epoch time time_here = time.localtime() print(time_here) for i in time_here: print(i) print(time_here[0])
true
91bfc92d73cf257344dc1260e433bdbd9d6cb4d5
DeepanshuSarawagi/python
/freeCodeCamp/ConditionalExecution/conditionalExecution.py
309
4.1875
4
# This is a python exercise on freeCodeCamp's python certification curriculum x = 5 if x < 5: print("X is less than 5") for i in range(5): print(i) if i <= 2: print("i is less than or equal to 2") if i > 2: print("i is now ", i) print("Done with ", i) print("All done!")
true
7384fbb693486ec0f00158292487d6a2086fc2ac
DeepanshuSarawagi/python
/Data Types/numericOperators.py
485
4.34375
4
# In this lesson we are going to learn about the numeric operators in the Python. a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) # We will learn about the operator precedence in the following example. print(a + b / 3 - 4 * 12) # This should evaluate to -35.0 as per the BODMAS rule. If you have got it 12, you are wrong. print(a + (b/3) - (4 * 12)) print((((a + b) / 3) - 4) * 12) # This will evaluate to 12.0. print(a / (b * a) / b)
true
6d34356e7e6d161aa6e838b8ca588e3dce3b01f4
DeepanshuSarawagi/python
/100DaysOfPython/Day2/DataTypes/typeConversion.py
944
4.25
4
# In this lesson we are going to convert the int data type to string data type num_char = len(input("What is your name?\n")) print("Your name has " + str(num_char) + " characters") # Type conversion happens here. Where we convert # the type integer to string # Or we can use the fStrings print("Your name has {} characters".format(num_char)) print(70 + float("170.5")) # Day 2 - Exercise 1 - Print the sum of digits of a number two_digit_number = input("Type a two digit number of your choice: ") print(int(two_digit_number[0]) + int(two_digit_number[1])) # Better solution sum_of_numbers = 0 for i in range(0, len(str(two_digit_number))): sum_of_numbers += int(two_digit_number[i]) print(sum_of_numbers) # Remembering the PEMDASLR rule (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction, Left to Right) print(3 * 3 + 3 / 3 - 3) print(3 * 3 / 3 + 3 - 3)
true
a9aaf4e426597e6a54aff443fdadefad6e4fb9d6
DeepanshuSarawagi/python
/100DaysOfPython/Day1/main.py
647
4.375
4
print("Print something") print("Hello World!") print("Day 1 - Python Print Function") print("print('what to print')") print("Hello World!\nHello World again!\nHellooo World!!") print() # Day 1. Exercise 2 Uncomment below and debug the errors # print(Day 1 - String Manipulation") # print("String Concatenation is done with the "+" sign.") # print('e.g. print("Hello " + "world")') # print(("New lines can be created with a backslash and n.") print("Day 1 - String Manipulation") print("String Concatenation is done with the " + "+" + " sign.") print('e.g. print("Hello " + "world")') print("New lines can be created with a backslash and n.")
true
34c3bcf8c09826d88ff52370f8c9ae9735d2f966
DeepanshuSarawagi/python
/100DaysOfPython/Day19/Turtle-GUI-2/main.py
796
4.21875
4
from turtle import Turtle, Screen tim = Turtle() screen = Screen() def move_forward(): tim.forward(10) screen.listen() # In order for our turtle to listen to the screen events, we need to call this screen method screen.onkey(fun=move_forward, key="Up") # The Screen.onkey() method accepts two arguments, 1. Function and 2. Kwy. # We need to ensure that when we pass a function as an argument, it is coded without parentheses. Passing the function # with parentheses calls the function immediately, instead we want it listen to an event and call the function when an # event occurs. Like for example, in our case, when a key is presses. screen.exitonclick() # Higher Order Functions. A higher Order Function is called when a function accepts another function as an # input/argument
true
e9e42890ea221e41dd51181364f24590d1b0ce6e
DeepanshuSarawagi/python
/whileLoop/whileLoop.py
423
4.125
4
# In this lesson we are going to learn about while loops in Python. # Simple while loop. i = 0 while i < 10: print(f"i is now {i}") i += 1 available_exit =["east", "west", "south"] chosen_exit = "" while chosen_exit not in available_exit: chosen_exit = input("Please enter a direction: ") if chosen_exit == "quit": print("Game over") break else: print("Glad that you got out of here")
true
11bc279d354a5d57bcae0bd9d14b8ed52db97a4b
DeepanshuSarawagi/python
/100DaysOfPython/Day27/ArgsAndKwargs/kwargs_example.py
1,160
4.6875
5
""" In this lesson we are going to learn about unlimited keyword arguments and how it can be used in functions. The general syntax is to define a function with just one parameter **kwargs. We can then loop through the 'many' keyword arguments and perform necessary actions. Syntax: def function(**kwargs): some operation """ def calculate(**kwargs): for key in kwargs: print(f"{key}: {kwargs[key]}") calculate(add=5, subtract=6, multiply=10, divide=2) def calculate(n, **kwargs): n += kwargs["add"] print(n) n -= kwargs["subtract"] print(n) n *= kwargs["multiply"] print(n) n /= kwargs["divide"] print(n) calculate(n=10, add=5, subtract=6, multiply=10, divide=2) """Similarly we can use **kwargs in the __init__ method while creating a class. Refer to below exmaple""" class Car: def __init__(self, **kwargs): self.model = kwargs["model"] self.make = kwargs["make"] def print_car_details(self): print("You created a car. Your car make is {} and model is {}.".format(self.make, self.model)) my_car = Car(make="BMW", model="GT") my_car.print_car_details()
false
ad0cf84f3a01da48c32aa7efae44cf3b964d44d1
DeepanshuSarawagi/python
/100DaysOfPython/Day2/DataTypes/BMICalculator.py
209
4.28125
4
height = float(input("Enter your height in meters: ")) weight = float(input("Enter your weight in kilograms: ")) print("Your BMI is {}".format(round(weight / (height * height), 2))) print(8 // 3) print(8 / 3)
true
31a342ddff6fade8595b45f6127868b7525feca1
DeepanshuSarawagi/python
/DSA/Arrays/TwoDimensionalArrays/main.py
2,074
4.40625
4
import numpy # Creating two dimensional arrays # We will be creating it using a simple for loop two_d_array = [] for i in range(1, 11): two_d_array.append([i * j for j in range(2, 6)]) print(two_d_array) twoDArray = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) print(twoDArray) # Insertion in 2D array new2DArray = numpy.insert(twoDArray, 1, [[21, 22, 23, 24]], axis=1) # The first int parameter is the position # where we want to add. And axis=1 denotes we want to add new values as columns, if axis=0, add it as rows # Important Note: While using numpy library to insert elements in a 2-D array is that we meed to match the # row/column size while inserting new elements in array print(new2DArray) # We will now use the append function to insert a new row/column at the end of the array new2D_Array = numpy.append(twoDArray, [[97], [98], [99], [100]], axis=1) print(new2D_Array) print(len(new2D_Array)) # This prints the no. of rows in an array print(len(new2D_Array[0])) # This prints the no. of columns in an array def access_elements(array, rowIndex: int, colIndex: int) -> None: if rowIndex >= len(array) and colIndex >= len(array[0]): print("You are trying to access an element which is not present in the array") else: print(array[rowIndex][colIndex]) access_elements(new2D_Array, 3, 5) # Traversing through the 2-D array def traverse_array(array): for i in range(len(array)): for j in range(len(array[0])): print(array[i][j], end="\t") print() traverse_array(new2D_Array) def search_element(element, array): for i in range(len(array)): for j in range(len(array[0])): if array[i][j] == element: return "{} found at row {} and column {}".format(element, i + 1, j + 1) return "The element {} is not found in given array.".format(element) print(search_element(15, new2D_Array)) # How to delete a row/column in 2-D array new2D_Array = numpy.delete(twoDArray, 0, axis=0) print(new2D_Array)
true
4bde74d331959c0b3ca9002de605e7b39066c22d
DeepanshuSarawagi/python
/100DaysOfPython/Day3/IfElseAndConditionaloperators/BMICalculator.py
575
4.375
4
# BMI calculator 2.0 height = float(input("Please enter your height in meters: ")) weight = float(input("Please enter your weight in kgs: ")) bmi = float(round(weight / (height ** 2), 2)) if bmi < 18.5: print("BMI = {:.2f}. You are underweight".format(bmi)) elif 18.5 <= bmi <= 25: print("BMI = {:.2f}. You are normal weight.".format(bmi)) elif 25 < bmi <= 30: print("BMI = {:.2f}. You are overweight.".format(bmi)) elif 30 < bmi <= 35: print("BMI = {:.2f}. You are obese.".format(bmi)) else: print("BMI = {:.2f}. You are clinically obese.".format(bmi))
false
c32944fc92021af6a9aab1d68844287921f5f7dd
DeepanshuSarawagi/python
/100DaysOfPython/Day21/InheritanceBasics/Animal.py
563
4.375
4
class Animal: def __init__(self): self.num_eyes = 2 def breathe(self): print("Inhale, Exhale") # Now we are going to create a class Fish which will inherit properties from the Animal class and also has it's own # properties class Fish(Animal): def __init__(self): super().__init__() # Initializing all the attributes in super class self.num_eyes = 3 # Here we are changing the field num_eyes to 3 def swim(self): print("I can swin in water") def print_eyes(self): print(self.num_eyes)
true
1117ab86b491eca4f879897af51ccc69112e854b
shaonsust/Algorithms
/sort/bubble_sort.py
1,074
4.40625
4
""" Python 3.8.2 Pure Python Implementation of Bubble sort algorithm Complexity is O(n^2) This algorithm will work on both float and integer type list. Run this file for manual testing by following command: python bubble_sort.py Tutorial link: https://www.geeksforgeeks.org/bubble-sort/ """ def bubble_sort(arr): """ Take an unsorted list and return a sorted list. Args: arr (integer) -- it could be sorted or unsorted list. Returns: arr (integer) -- A sorted list. Example: >>> bubble_sort([5, 4, 6, 8 7 3]) [3, 4, 5, 6, 7, 8] """ for i in range(len(arr) - 1): flag = True for j in range(len(arr) - i - 1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] # Swaping here flag = False if flag: break return arr if __name__ == '__main__': # Taking input from user USER_INPUT = [float(x) for x in input().split()] # call bublesort to sort an unsorted list and print it. print(bubble_sort(USER_INPUT))
true
a0118ebfc3e690eb89439727e45ac0c5085c382d
destinysam/Python
/step_argument_slicing.py
769
4.40625
4
# CODED BY SAM@SAMEER # EMAIL: SAMS44802@GMAIL.COM # DATE: 15/08/2019 # PROGRAM: STEP ARGUMENT IN STRING SLICING language = "programming language" print("python"[0:6]) print("python"[0:6:1]) # SYNTAX STRING_NAME[START ARGUMENT:STOP ARGUMENT:STEP] print("python"[0:6:2]) # TAKING 2 STEPS TO AHEAD TO PRINT POSITION[2] AND CONTINUE THIS PROCESS print("python"[0:6:3]) # TAKING 3 STEPS TO AHEAD TO PRINT POSITION[4] AND CONTINUE THIS PROCESS print("python"[0:6:4]) print("python"[0:6:5]) print("python"[::-1]) # REVERSING THE STRING print(language[::-1]) print(language[0:20]) # print(language[0:20:2]) # TAKING 2 STEPS TO AHEAD TO PRINT POSITION[2] AND CONTINUE THIS PROCESS print(language[0:20:3]) name = input('ENTER THE NAME ') print("THE REVERSE OF NAME IS " + name[::-1])
false
81a8bce1fd4ad1426104d8f4b662f0c0ca3c52c5
destinysam/Python
/more inputs in one line.py
435
4.15625
4
# CODED BY SAM@SAMEER # EMAIL: SAMS44802@GMAIL.COM # DATE: 12/09/2019 # PROGRAM: TAKING MORE THAN ONE INPUT FROM THE USER name, age, address = "sameer", "23", "tarigam" # ASSIGNING VALUES BY ORDER print("YOUR NAME,AGE AND ADDRESS IS " + name + " " + age + " " + address) x = y = z = 2 print(x+y+z) name, age, address = input("ENTER YOUR NAME AND AGE ").split() # USING OF SPLIT FUNCTION TO TAKE MORE INPUTS print(name) print(age) print(address)
true
0eaf2afa9cc1c3f161504fc2c9254b92fb3f4262
venkatadri123/Python_Programs
/100_Basic_Programs/program_43.py
280
4.53125
5
# 43. Write a program which accepts a string as input to print "Yes" # if the string is "yes" or "YES" or "Yes", otherwise print "No". def strlogical(): s=input() if s =="Yes" or s=="yes" or s=="YES": return "Yes" else: return "No" print(strlogical())
true
01158919c0c3b66a38f8094fe99d22d9d3f53bed
venkatadri123/Python_Programs
/100_Basic_Programs/program_35.py
322
4.15625
4
# 35. Define a function which can generate a dictionary where the keys are numbers between 1 and 20 # (both included) and the values are square of keys. The function should just print the keys only. def sqrkeys(): d=dict() for i in range(1,21): d[i]=i**2 for k in d: print(k) sqrkeys()
true
b1adffe626fa1a1585012689ec2b1c01925c181c
venkatadri123/Python_Programs
/core_python_programs/prog78.py
334
4.15625
4
# Write a python program to accept values from keyboard and display its transpose. from numpy import* r,c=[int(i) for i in input('enter rows,columns:').split()] arr=zeros((r,c),dtype=int) print('enter the matrix:') for i in range(r): arr[i]=[int(x) for x in input().split()] m=matrix(arr) print('transpose:') print(m.transpose())
true
3625b577e1d82afc31436473149cc7ff1e3ce96c
venkatadri123/Python_Programs
/100_Basic_Programs/program_39.py
318
4.1875
4
# 39. Define a function which can generate a list where the values are square of numbers # between 1 and 20 (both included). Then the function needs to print all values # except the first 5 elements in the list. def sqrlis(): l=[] for i in range(1,20): l.append(i**2) return l[5:] print(sqrlis())
true
fa7b092a720e7ce46b2007341f4e70de60f8e6ca
venkatadri123/Python_Programs
/100_Basic_Programs/program_69.py
375
4.15625
4
# 69. Please write assert statements to verify that every number in the list [2,4,6,8] is even. l=[2,4,6,8] for i in l: assert i%2==0 # Assertions are simply boolean expressions that checks if the conditions return true or not. # If it is true, the program does nothing and move to the next line of code. # However, if it's false, the program stops and throws an error.
true
7a26e4bc77d34fd19cf4350c78f4764492d32064
venkatadri123/Python_Programs
/core_python_programs/prog83.py
250
4.25
4
# Retrive only the first letter of each word in a list. words=['hyder','secunder','pune','goa','vellore','jammu'] lst=[] for ch in words: lst.append(ch[0]) print(lst) # To convert into List Comprehension. lst=[ch[0] for ch in words] print(lst)
true
b1c41d7bfbc80bdd15642bcb0f02291c7867779e
ProgrammingForDiscreteMath/20170830-bodhayan
/code.py
700
4.15625
4
# 1 # Replace if-else with try-except in the the example below: def element_of_list(L,i): """ Return the 4th element of ``L`` if it exists, ``None`` otherwise. """ try: return L[i] except IndexError: return None # 2 # Modify to use try-except to return the sum of all numbers in L, # ignoring other data-types def sum_of_numbers(L): """ Return the sum of all the numbers in L. """ s = 0 for l in L: try: s+= l except TypeError: pass return s # TEST # print sum_of_numbers([3, 1.9, 's']) == 4.9 # L1 = [1,2,3] # L2 = [1,2,3,4] # print fourth_element_of_list(L1) # print fourth_element_of_list(L2)
true
b6834d2bf0af216c26a7a2b92880ab566685caea
planetblix/learnpythonthehardway
/ex16.py
1,436
4.40625
4
#/bin/python from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Open the file..." #rw doesn't mean read and write, it just means read! #You could open the file twice, but not particularly safe, #As you could overwrite the file. target = open(filename, 'r+') #Other file modes: #'r' - open for read only #'r+' - open for read and write, cannot truncate #'rb - reading binary #'rb+ - reading or writing a binary file #'w' - open for write only #'w+' - open fo read and write, can truncate #'a' - open for append only #'a+' - open for reading and writing. #'U' - opens file for input with Universal newline input. #Based on C fopen(): http://www.manpagez.com/man/3/fopen/ #Nice examples here: http://www.tutorialspoint.com/python/python_files_io.htm print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1:") line2 = raw_input("line 2:") line3 = raw_input("line 3:") print "I'm going to write these to the file." #target.write(line1) #target.write("\n") #target.write(line2) #target.write("\n") #target.write(line3) #target.write("\n") target.write("%s\n" % line1) target.write("%s\n" % line2) target.write("%s\n" % line3) print target.read() print "And finally, we close it." target.close()
true
9522b6a465c1644ff8399a838eb3a7fb3b9cbcec
seriouspig/homework_week_01_day_01
/precourse_recap.py
566
4.15625
4
print("Guess the number I'm thinking from 1 to 10, What do you think it is?") guessing = True number_list = [1,2,3,4,5,6,7,8,9,10] import random selected_number = random.choice(number_list) while guessing == True: answer = int(input('Pick a number from 1 to 10: ')) if answer == selected_number: print("Great, you must be a psychic!") guessing = False break elif answer < selected_number: print("No, my number is higher, try again") elif answer > selected_number: print("No, my number is lower, try again")
true
961b6639cb292351bff3d4ded8c366ab0d860ed8
IshaqNiloy/Any-or-All
/main (1).py
980
4.25
4
def is_palindromic_integer(my_list): #Checking if all the integers are positive or not and initializing the variable is_all_positive = all(item >= 0 for item in my_list) #Initializing the variable is_palindrome = False if is_all_positive == True: for item in my_list: #Converting the integer into a string and reversing it item_str = str(item)[::-1] #Checking weather the string is a palindrome or not if str(item) == item_str: is_palindrome = True #Printing the result if is_all_positive == True and is_palindrome == True: print('True') else: print('False') if __name__ == '__main__': #Defining an empty list my_list = [] #taking input for the number of integers number_of_integers = input() #taking input for the list my_list = list(map(int, input().split())) #Calling the function is_palindromic_integer(my_list)
true
de3f02e8416760c40ab208ff7ee372313040fcd1
bishal-ghosh900/Python-Practice
/Practice 1/main30.py
992
4.1875
4
# Sieve of Eratosthenes import math; n = int(input()) def findPrimes(n): arr = [1 for i in range(n+1)] arr[0] = 0 arr[1] = 0 for i in range(2, int(math.sqrt(n)) + 1, 1): if arr[i] == 1: j = 2 while j * i <= n: arr[j*i] = 0 j += 1 for index, value in enumerate(arr): # enumerate will give tuples for every iteration which will contain index and value of that particular iteration coming from the list . And in this particular list the tuple is being unpacked in the index and the value variable # Its something like --> index, value = ("0", 1) # index, value = ("1", 2) and so on # "0", "1", "2" etc are the indexs of the list, and the next argument is the value of that particular index from the list in which we are performing enumerate() operation. if value == 1: print(index, sep=" ") else: continue findPrimes(n)
true
eaadca4eda12fc7af10c3a6f70437a760c14358f
bishal-ghosh900/Python-Practice
/Practice 1/main9.py
595
4.6875
5
# Logical operator true = True false = False if true and true: print("It is true") # and -> && else: print("It is false") # and -> && # Output --> It is true if true or false: print("It is true") # and -> || else: print("It is false") # and -> || # Output --> It is true if true and not true: print("It is true") # and -> && # not -> ! else: print("It is false") # and -> && # Output --> It is false if true or not true: print("It is true") # and -> && # not -> ! else: print("It is false") # and -> && # Output --> It is true
true
460ea4d25a2f8d69e8e009b70cdec588b8ca7b20
bishal-ghosh900/Python-Practice
/Practice 1/main42.py
782
4.28125
4
# set nums = [1, 2, 3, 4, 5] num_set1 = set(nums) print(num_set1) num_set2 = {4, 5, 6, 7, 8} # in set there is not any indexing , so we can't use expression like num_set1[0]. # # Basically set is used to do mathematics set operations #union print(num_set1 | num_set2) # {1, 2, 3, 4, 5, 6, 7, 8} # intersection print(num_set1 & num_set2) # {4, 5} # A - B --> Every element of A but not of B print(num_set1 - num_set2) # {1, 2, 3} # B - A --> Every element of B but not of A print(num_set2 - num_set1) # {8, 6, 7} # symmetric difference --> (A - B) U (B - A) --> Every thing present in A and B but not in both print(num_set1 ^ num_set2) # {1, 2, 3, 6, 7, 8} # like list we can also create set comprehension nums = { i * 2 for i in range(5)} print(nums) # {0, 2, 4, 6, 8}
true
789e675cb561a9c730b86b944a0a80d6c423f475
bishal-ghosh900/Python-Practice
/Practice 1/main50.py
804
4.75
5
# private members # In python there we can prefix any data member with __ (dunder sign) , then it will be private. In reality it don't get private, if we declare any data member with __ , that data member actually get a differet name from python , which is like => _classname__fieldname. So in the below implementation if we change "eyes" field member to "__eyes" , then python will change it to "_Animal__eyes" . We can't access "eyes" by using "a.eyes" (here think "a" is Animal object) as eyes is changed to "_Animal__eyes" , so if we want to access "eyes", then we have to access it by using "a._Animal__eyes" class Animal: def run(self): print("I can run") __eyes = 2 a = Animal() # print(a.eyes) => error -> Animal object has no attribute eyes print(a._Animal__eyes) # 2 a.run()
true
c35759cf6ddf382cd6ec14e90bd013707af13fd6
learninfo/pythonAnswers
/Task 5 - boolean.py
236
4.375
4
import turtle sides = int(input("number of sides")) while (sides < 3) or (sides > 8) or (sides == 7): sides = input("number of sides") for count in range(1, sides+1): turtle.forward(100) turtle.right(360/sides)
true
a8a5edf3c6cf3f5a6470016eb6c5802e18df4338
bharath-acchu/python
/calci.py
899
4.1875
4
def add(a,b): #function to add return (a+b) def sub(a,b): return (a-b) def mul(a,b): return (a*b) def divide(a,b): if(b==0): print("divide by zero is not allowed") return 0 else: return (a/b) print('\n\t\t\t SIMPLE CALCULATOR\n') while 1: print('which operation you want to ?\n') print('1.addition\n2.subtraction\n3.multiplication\n4.division\n') ch=int(input('ENTER YOUR CHOICE\n')) a=float(input("Enter first number\n")) b=float(input("Enter second number\n")) if ch is 1: #is also used as equality operator print("ans=",add(a,b)) elif(ch==2): print("ans=",sub(a,b)) elif(ch==3): print("ans=",mul(a,b)) elif(ch==4): print("ans=",divide(a,b)) else:print("improper choice\n")
true
85be56b1f4f0ae5e51463b8ef7005fcef33fa357
parasmaharjan/Python_DeepLearning
/ICP4/ClassObject.py
1,226
4.125
4
# Python Object-Oriented Programming # attribute - data # method - function associated with class # Employee class class Employee: # special init method - as initialize or constructor # self == instances def __init__(self, first, last, pay, department): self.first = first self.last = last self.pay = pay self.department = department def fullname(self): return ('{} {}'.format(self.first, self.last)) # Instance variable emp_1 = Employee('Paras','Maharjan', 50000, 'RnD') #print(emp_1) emp_2 = Employee('Sarap', 'Maharjan', 70000, 'Accounts') #print(emp_2) # print(emp_1.first, ' ', emp_1.last, ', ', emp_1.department, ', ', emp_1.pay) # print(emp_2.first, ' ', emp_2.last, ', ', emp_2.department, ', ', emp_2.pay) # print using place holder print('First name\tLast name\tSalary($)\tDepartment') print('----------------------------------------------') print('{}\t\t{}\t{}\t\t{}'.format(emp_1.first, emp_1.last, emp_1.pay, emp_1.department)) print('{}\t\t{}\t{}\t\t{}'.format(emp_2.first, emp_2.last, emp_2.pay, emp_2.department)) # class instance is pass argument to method, so we need to use self # print(Employee.fullname(emp_1)) # print(emp_2.fullname())
false
49629b071964130f6fb9034e96480f7b5a179e51
aakhriModak/assignment-1-aakhriModak
/01_is_triangle.py
2,117
4.59375
5
""" Given three sides of a triangle, return True if it a triangle can be formed else return False. Example 1 Input side_1 = 1, side_2 = 2, side_3 = 3 Output False Example 2 Input side_1 = 3, side_2 = 4, side_3 = 5 Output True Hint - Accordingly to Triangle inequality theorem, the sum of any two sides of a triangle must be greater than measure of the third side """ import unittest # Implement the below function and run this file # Return the output, No need read input or print the ouput def is_triangle(side_1, side_2, side_3): # write your code here if side_1>0 and side_2>0 and side_3>0: if side_1+side_2>side_3 and side_2+side_3>side_1 and side_1+side_3>side_2: return True else: return False else: return False # DO NOT TOUCH THE BELOW CODE class TestIsTriangle(unittest.TestCase): def test_01(self): self.assertEqual(is_triangle(1, 2, 3), False) def test_02(self): self.assertEqual(is_triangle(2, 3, 1), False) def test_03(self): self.assertEqual(is_triangle(3, 1, 2), False) def test_04(self): self.assertEqual(is_triangle(3, 4, 5), True) def test_05(self): self.assertEqual(is_triangle(4, 5, 3), True) def test_06(self): self.assertEqual(is_triangle(5, 3, 4), True) def test_07(self): self.assertEqual(is_triangle(1, 2, 5), False) def test_08(self): self.assertEqual(is_triangle(2, 5, 1), False) def test_09(self): self.assertEqual(is_triangle(5, 1, 2), False) def test_10(self): self.assertEqual(is_triangle(0, 1, 1), False) def test_11(self): self.assertEqual(is_triangle(1, 0, 1), False) def test_12(self): self.assertEqual(is_triangle(1, 1, 0), False) def test_13(self): self.assertEqual(is_triangle(-1, 1, 2), False) def test_14(self): self.assertEqual(is_triangle(1, -1, 2), False) def test_15(self): self.assertEqual(is_triangle(1, 1, -2), False) if __name__ == '__main__': unittest.main(verbosity=2)
true
5097aa5c089e31d239b06bbd76e99942694cbdd7
CBehan121/Todo-list
/Python_imperative/todo.py
2,572
4.1875
4
Input = "start" wordString = "" #intializing my list while(Input != "end"): # Start a while loop that ends when a certain inout is given Input = input("\nChoose between [add], [delete], [show list], [end] or [show top]\n\n") if Input == "add": # Check if the user wishes to add a new event/task to the list checker = input("\nWould you Task or Event?\n") # Take the task/event input if checker.lower() == "task": words = input("Please enter a Date.\n") + " " words += input("Please enter a Start time.\n") + " " words += input("Please enter a Duration.\n") + " " words += input("Please enter a list of members. \n") wordString = wordString + words + "!" # Add the new task/event to the list. I use a ! to seperate each item. elif checker.lower() == "event": words = input("Please enter a Date, Start time and Location\n") + " " words += input("Please enter a Start time. \n") + " " words += input("Please enter a loaction. \n") wordString = wordString + words + "!" # Add the new task/event to the list. I use a ! to seperate each item. else: print("you failed to enter a correct type.") elif Input == "show top": if wordString != "": # Enure there is something in your list already i = 0 while wordString[i] != "!": # iterates until i hit a ! which means ive reached the end of an item i += 1 print("\n\n" + wordString[:i] + "\n") # print the first item in the list else: print("\n\nYour list is empty.\n") elif Input == "delete": if wordString != "": #the try is put in place incase the string is empty. i = 0 while wordString[i] != "!": # iterate until i reach the end of the first task/event i += 1 wordString = wordString[i + 1:] #make my list equal from the end of the first item onwards else: print("\n\nYour list is already empty.\n") elif Input == "show list": if wordString != "": fullList = "" # create a new instance of the list so i can append \n inbetween each entry. i = 0 # Normal counter j = 0 # holds the position when it finds a ! for letter in wordString: if letter == "!": fullList = fullList + wordString[j:i] + "\n" # appending each item to the new list seperated by \n j = i + 1 # this needs a + 1 so it ignores the actual ! i = i + 1 print("\n\n" + fullList) else: print("\n\nYour list is empty\n") elif Input == "end": print("exiting program") else: print("\nYour input wasnt correct please try again\n") # This is just in place to catch any incorrect inputs you may enter.
true
813e9e90d06cb05c93b27a825ac14e5e96abcc9b
bparker12/code_wars_practice
/squre_every_digit.py
520
4.3125
4
# Welcome. In this kata, you are asked to square every digit of a number. # For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. # Note: The function accepts an integer and returns an integer def square_digits(num): dig = [int(x) **2 for x in str(num)] dig = int("".join([str(x) for x in dig])) print(dig) square_digits(9119) # more efficient def square_digits1(num): print(int(''.join(str(int(d)**2) for d in str(num)))) square_digits1(8118)
true
312b662283a4f358cfaeec5bfd0e7793bf03816d
unisociesc/Projeto-Programar
/Operadores/Exercícios Aritméticos.py
994
4.21875
4
#Exercícios Operadores Aritméticos # 1- Faça um Programa que peça dois números e imprima a soma. print('Soma de valores...\n') num1 = float(input('Digite um número: ')) num2 = float(input('Digite outro número: ')) soma = num1 + num2 #%s = string #%d = inteiros #%f = floats #%g = genéricos print('O resultado da soma de', num1,'+', num2,'é', soma) print('O resultado da soma de %g + %g é %g' % (num1,num2,soma)) # 2- Faça um Programa que peça as 4 notas bimestrais e mostre a média. n1 = float(input('Digite a nota 1: ')) n2 = float(input('Digite a nota 2: ')) n3 = float(input('Digite a nota 3: ')) n4 = float(input('Digite a nota 4: ')) media = n1 + n2 + n3 + n4 / 4 print('A média do aluno foi %g' % media) # 3- Faça um Programa que converta metros para centímetros. metros = float(input('Digite o valor em metros que queira converter: ')) convertido = metros * 100 print('O valor convertido de %g metros para centímetros é %g cm' % (metros, convertido))
false
f9b9cc936f7d1596a666d0b0586e05972e94cefa
jamiekiim/ICS4U1c-2018-19
/Working/practice_point.py
831
4.375
4
class Point(): def __init__(self, px, py): """ Create an instance of a Point :param px: x coordinate value :param py: y coordinate value """ self.x = px self.y = py def get_distance(self, other_point): """ Compute the distance between the current obejct and another Point object :param other_point: Point object to find the distance to :return: float """ distance = math.sqrt((other_point.x - self.x)**2 + (other_point.y - self.y)**2) return distance def main(): """ Program demonstrating the creation of Point instances and calling class methods. """ p1 = Point(5, 10) p2 = Point(3, 4) dist = p1.get_distance(p2) print("The distance between the points is" + str(dist)) main()
true
318a80ce77b542abc821fa8ff2983b0760da2838
aaronstaclara/testcodes
/palindrome checker.py
538
4.25
4
#this code will check if the input code is a palindrome print('This is a palindrome checker!') print('') txt=input('Input word to check: ') def palindrome_check(txt): i=0 j=len(txt)-1 counter=0 n=int(len(txt)/2) for iter in range(1,n+1): if txt[i]==txt[j]: counter=counter+1 i=i+iter j=j-iter if counter==n: disp="Yes! It is a palindrome!" else: disp='No! It is not a palindrome!' return print(disp) palindrome_check(txt)
true
f0754dfa5777cd2e69afa26e2b73b216d0ff5313
sb1994/python_basics
/vanilla_python/lists.py
346
4.375
4
#creating lists #string list friends = ["John","Paul","Mick","Dylan","Jim","Sara"] print(friends) #accessing the index print(friends[2]) #will take the selected element and everyhing after that print(friends[2:]) #can select a range for the index print(friends[2:4]) #can change the value at specified index friends[0] = "Toby" print(friends)
true
1deb78c1b1af35d46bf3fef07643a25ba7a1c5f1
naveen882/mysample-programs
/classandstaticmethod.py
2,569
4.75
5
""" Suppose we have a class called Math then nobody will want to create object of class Math and then invoke methods like ceil and floor and fabs on it.( >> Math.floor(3.14)) So we make them static. One would use @classmethod when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method. While using static you would want the behaviour to remain unchanged across subclasses http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner/31503491#31503491 Example: """ class Hero: @staticmethod def say_hello(): print("Helllo...") @classmethod def say_class_hello(cls): if(cls.__name__=="HeroSon"): print("Hi Kido") elif(cls.__name__=="HeroDaughter"): print("Hi Princess") class HeroSon(Hero): def say_son_hello(self): print("test hello") class HeroDaughter(Hero): def say_daughter_hello(self): print("test hello daughter") testson = HeroSon() testson.say_class_hello() testson.say_hello() testdaughter = HeroDaughter() testdaughter.say_class_hello() testdaughter.say_hello() print "============================================================================" """ static methods are best used when you want to call the class functions without creating the class object """ class A(object): @staticmethod def r1(): print "In r1" print A.r1() #In r1 a=A() a.r1() #In r1 class A(object): def r1(self): print "In r1" """ print A.r1() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method r1() must be called with A instance as first argument (got nothing instead) """ print "============================================================================" class dynamo(): @staticmethod def all_return_same(): print "static method" @classmethod def all_return_different(cls): print cls if cls.__name__ == 'A': print "1" elif cls.__name__ == 'B': print "2" else: print "3" class A(dynamo): pass class B(dynamo): pass d=dynamo() d.all_return_same() d.all_return_different() dynamo().all_return_same() dynamo().all_return_different() print "======" a=A() a.all_return_same() a.all_return_different() A.all_return_same() A.all_return_different() print "======" b=B() b.all_return_same() b.all_return_different() B.all_return_same() B.all_return_different() print "============================================================================"
true
fc8bde15b9c00120cb4d5b19920a58e288100686
CHemaxi/python
/003-python-modules/008-python-regexp.py
2,984
4.34375
4
""" MARKDOWN --- Title: python iterators and generators MetaDescription: python regular, expressions, code, tutorials Author: Hemaxi ContentName: python-regular-expressions --- MARKDOWN """ """ MARKDOWN # PYTHON REGULAR EXPRESSIONS BASICS * Regular Expressions are string patterns to search in other strings * PYTHON Regular Expressions, functionality is provided by the "re" MODULE * The "re" Module provides all the functions required to enable PYTHONs regular expressions * Regular expressions is all about matching a "pattern" in a "string" * **search()** function, returns true or false for the string found / not found * **findall()** function, returns a TUPLE of all occurrences of the pattern * **sub()** function, This is used to replace parts of strings, with a pattern * **split()** function, seperates a string by space or any dilimeter. MARKDOWN """ # MARKDOWN ``` ####################### # 1) search Function ####################### import re # Create a test string with repeating letters words test_string = "The Test string 123 121212 learnpython LEARNPYTHON a1b2c3" #Search for pattern: learnpython (in SMALL LETTERS) match = re.search(r'learnpython',test_string) if match: print("The word 'learnpython' is found in the string:", "\n", test_string) else: print("The word 'learnpython' is NOT found in the string:", "\n", test_string) # Search for more complicated patterns, search for 12*, where * # is wildcard character, match everything else after the pattern "12" match = re.search(r'12*',test_string) if match: print("The word '12*' is found in the string:", "\n", test_string) else: print("The word '12*' is NOT found in the string:", "\n", test_string) ######################## # 2) findall Function ######################## import re # Prints all the WORDS with a SMALL "t" in the test-string # The options are: # word with a "t" in between \w+t\w+, # OR indicated by the PIPE symbol | # word with a "t" as the last character \w+t, # OR indicated by the PIPE symbol | # word with a "t" as the first character t\w+, # Create a test string with repeating letters words test_string = "The Test string 123 121212 learnpython LEARNPYTHON a1b2c3" all_t = re.findall(r'\w+t\w+|\w+t|t\w+',test_string) # The re.findall returns a TUPLE and we print all the elements looping # through the tuple for lpr in all_t: print(lpr) ######################## # 3) sub Function ######################## import re # This is used to replace parts of strings, with a pattern string = "Learnpython good python examples" # Replace "good" with "great" new_string = re.sub("good", "great", string) print(string) print(new_string) ######################## # 4) split Function ######################## # The split Function splits a string by spaces import re words2list = re.split(r's','Learnpython good python examples') print(words2list) # Split a Comma Seperated String csv2list = re.split(r',','1,AAA,2000') print(csv2list) # MARKDOWN ```
true
bcd7c3ee14dd3af063a6fea74089b02bade44a1c
hussein343455/Code-wars
/kyu 6/Uncollapse Digits.py
729
4.125
4
# ask # You will be given a string of English digits "stuck" together, like this: # "zeronineoneoneeighttwoseventhreesixfourtwofive" # Your task is to split the string into separate digits: # "zero nine one one eight two seven three six four two five" # Examples # "three" --> "three" # "eightsix" --> "eight six" # "fivefourseven" --> "five four seven" # "ninethreesixthree" --> "nine three six three" # "fivethreefivesixthreenineonesevenoneeight" --> "five three def uncollapse(digits): x=["zero","one","two","three","four","five","six","seven","eight","nine"] for ind,i in enumerate(x): digits=digits.replace(i,str(ind)) return " ".join([x[int(i)] for i in digits])
true
ab31c3e1a33bbe9ec2eb8ef5235b2206c022a8d7
kritikhullar/Python_Training
/day1/factorial.py
288
4.25
4
#Fibonacci print("-----FIBONACCI-----") a= int(input("Enter no of terms : ")) def fibonacci (num): if num<=1: return num else: return (fibonacci(num-1)+fibonacci(num-2)) if a<=0: print("Enter positive") else: for i in range(a): print (fibonacci(i), end = "\t")
false
64e73cb395d25b53a166a6e491e70a7834c96aee
sajjadm624/Bongo_Python_Code_Test_Solutions
/Bongo_Python_Code_Test_Q_3.py
2,330
4.1875
4
# Data structure to store a Binary Tree node class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right # Function to check if given node is present in binary tree or not def isNodePresent(root, node): # base case 1 if root is None: return False # base case 2 # if node is found, return true if root == node: return True # return true if node is found in the left subtree or right subtree return isNodePresent(root.left, node) or isNodePresent(root.right, node) def preLCA(root, lca, x, y): # case 1: return false if tree is empty if root is None: return False, lca # case 2: return true if either x or y is found # with lca set to the current node if root == x or root == y: return True, root # check if x or y exists in the left subtree left, lca = preLCA(root.left, lca, x, y) # check if x or y exists in the right subtree right, lca = preLCA(root.right, lca, x, y) # if x is found in one subtree and y is found in other subtree, # update lca to current node if left and right: lca = root # return true if x or y is found in either left or right subtree return (left or right), lca # Function to find lowest common ancestor of nodes x and y def LCA(root, x, y): # lca stores lowest common ancestor lca = None # call LCA procedure only if both x and y are present in the tree if isNodePresent(root, y) and isNodePresent(root, x): lca = preLCA(root, lca, x, y)[1] # if LCA exists, print it if lca: print("LCA is ", lca.data) else: print("LCA do not exist") if __name__ == '__main__': """ Construct below tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(8) root.right.left.right = Node(9) LCA(root, root.right.left, root.right.right) LCA(root, root.right, root.right.right)
true
92156b23818ebacfa3138e3e451e0ed11c0dd343
brianspiering/project-euler
/python/problem_025.py
1,139
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "1000-digit Fibonacci number", Problem 25 http://projecteuler.net/problem=25 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? """ num_digits = 1000 # 3 | 1000 def fib(): "A Fibonacci sequence generator." a, b = 0, 1 while True: a, b = b, a+b yield a def find_fib_term(num_digits): "Find the 1st fib term that has the given number of digits." f = fib() current_fib = f.next() counter = 1 while len(str(current_fib)) < num_digits: current_fib = f.next() counter += 1 return counter if __name__ == "__main__": print("The first term in the Fibonacci sequence to contain {} digits "\ "is the {}th term." .format(num_digits, find_fib_term(num_digits)))
true
5448d28db97a609cafd01e68c875affe1f97723c
brianspiering/project-euler
/python/problem_004.py
992
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "Largest palindrome product", aka Problem 4 http://projecteuler.net/problem=4 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. """ low, high = 100, 999 # 10, 99 | 100, 999 def find_largest_palindrome(low, high): """(slightly) clever brute force method""" largest_palindrome = 0 for x in xrange(high,low-1,-1): for y in xrange(high,low-1,-1): if is_palindrome(x*y) and (x*y > largest_palindrome): largest_palindrome = x*y return largest_palindrome def is_palindrome(n): return str(n) == str(n)[::-1] if __name__ == "__main__": print("The largest palindrome made from the product of " + "two {0}-digit numbers is {1}." .format(len(str(low)), find_largest_palindrome(low, high)))
true
bd009da4e937a9cfc1c5f2e7940ca056c1969ae5
brianspiering/project-euler
/python/problem_024.py
1,489
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Solution to "Lexicographic permutations", Problem 24 http://projecteuler.net/problem=24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from __future__ import print_function import itertools # {range_argument: {place_number, place_name}} perm_picker = { 3: (6, 'sixth'), 10: (1000000, "millionth")} range_argument = 10 # 3 = demo; 10 def find_permutation(range_argument, place): "Find the specific (place) lexicographic permutation for give range argument." perm_tuple = list(itertools.permutations(xrange(range_argument)))[place-1] perm_string = "".join([str(n) for n in perm_tuple]) return perm_string if __name__ == "__main__": digits = range(range_argument) print("The {} lexicographic permutation of the digits ".format(perm_picker[range_argument][1], end="")) for digit in digits[:-2]: print("{}".format(digit), end=", ") print("{}".format(digits[-2]), end=", and ") print("{}".format(digits[-1]), end=" ") print("is {}.".format(find_permutation(range_argument, perm_picker[range_argument][0])))
true
5e2ae02f6553cbe7c31995ba76abf564c596d346
serenechen/Py103
/ex6.py
767
4.28125
4
# Assign a string to x x = "There are %d types of people." % 10 # Assign a string to binary binary = "binary" # Assign a string to do_not do_not = "don't" # Assign a string to y y = "Those who knows %s and those who %s." % (binary, do_not) # Print x print x # Print y print y # Print a string + value of x print "I said: %r." % x # Print a string + value of y print "I also said: '%s'." % y # Assign False to hilarious hilarious = False # Assign a string to joke_evaluation joke_evaluation = "Isn't that joke so funny?! %r" # Print a string + the value of hilarious print joke_evaluation % hilarious # Assign a string to w w = "This is the left side of..." # Assign a string to e e = "a string with a right side." # print a string concating w and e print w , e
true