blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7897869a67893a3ea72027ae8911e80e9e1d8f6a
Moandh81/python-self-training
/datetime/7.py
450
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program to print yesterday, today, tomorrow from datetime import datetime, date, time today = datetime.today() print("Today is " , today) yesterday = today.timestamp() - 60*60*24 yesterday = date.fromtimestamp(yesterday) print( "Yesterday is " , yesterday) tomorrow = today.timestamp() + 60*60*24 tomorrow = date.fromtimestamp(tomorrow) print("Tomorrow is ", tomorrow)
true
cdf3abaafdf05f6cc6a164b72120b100c010fe28
Moandh81/python-self-training
/sets/6.py
256
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program to create an intersection of sets. set1 = {"apple", "banana", "cherry" , "strawberry"} set2 = {"cherry", "ananas", "strawberry", "cocoa"} set3 = set1.intersection(set2) print(set3)
true
f552ed71c41a45b8838d36ca289e6ded418370f5
Moandh81/python-self-training
/tuple/12.py
355
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program to remove an item from a tuple. mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "duck" ,"bull", "sheep") myliste = [] txt = input("Please input a text : \n") for element in mytuple: if element != txt: myliste.append(element) myliste=tuple(myliste) print(myliste)
false
c05aca3c8637d78d9f31db8209ec7f3f1d6060cd
Moandh81/python-self-training
/functions/2.py
360
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -* # Write a Python function to sum all the numbers in a list. Go to the editor # Sample List : (8, 2, 3, 0, 7) # Expected Output : 20 liste = [1,2,3,4,5] def sumliste(liste): sum = 0 for item in liste: sum = sum + item print("The sum of the numbers in the list is {}".format(sum)) sumliste(liste)
true
4870640a39e9da3773c603ccb30b877b56c6c693
J-Krisz/project_Euler
/Problem 4 - Largest palindrome product.py
462
4.125
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. def is_palindrome(n): return str(n) == str(n)[::-1] my_list = [] for n_1 in range(100, 1000): for n_2 in range(100, 1000): result = n_1 * n_2 if is_palindrome(result): my_list.append(result) print(max(my_list))
true
4f05572563bd615a85bccc3d225f28b8a4ae36b5
djeikyb/learnpythonthehardway
/ex19a.py
1,298
4.125
4
# write a comment above each line explaining # define a function. eats counters for cheese and cracker boxen # shits print statements def cheese_and_crackers(cheese_count, boxes_of_crackers): # print var as decimal print "You have %d cheeses!" % cheese_count # print var as decimal print "You have %d boxes of crackers!" % boxes_of_crackers # print string print "Man that's enough for a party!" # print string print "Get a blanket.\n" # print string print "We can just give the function numbers directly:" # call function passing two decimals cheese_and_crackers(20, 30) # print string print "OR, we can use variables from our script:" # set cheese counter amount_of_cheese = 10 # set cracker boxen counter amount_of_crackers = 50 # call function passing cheese and cracker boxen count variables cheese_and_crackers(amount_of_cheese, amount_of_crackers) # print string print "We can even do math inside too:" # call function, passing two arguments. each argument uses elementary math cheese_and_crackers(10 + 20, 5 + 60) # print string print "And we can combine the two, variables and math:" # call function. each argument uses elementary algebra cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) # vim: syntax=off
true
44142626c57508d50cf1977411479703657439fc
stjohn/csci127
/errorsHex.py
1,179
4.21875
4
#CSci 127 Teaching Staff #October 2017 #A program that converts hex numbers to decimal, but filled with errors... Modified by: ADD YOUR NAME HERE define convert(s): """ Takes a hex string as input. Returns decimal equivalent. """ total = 0 for c in s total = total * 16 ascii = ord(c if ord('0) <= ascii <= ord('9'): #It's a decimal number, and return it as decimal: total = total+ascii - ord('0') elif ord('A") <= ascii <= ord('F'): #It's a hex number between 10 and 15, convert and return: total = total + ascii - ord('A') + 10 else ord('a') =< ascii <= ord('f'): #Check if they used lower case: #It's a hex number between 10 and 15, convert and return: total = total + ascii - ord('a') +++ 10 else: #Not a valid number! return(-1) return(total) def main() hexString = input("Enter a number in hex: ') prnt("The number in decimal is", convert(hexString)) #Allow script to be run directly: if __name__ == "__main__": main()
true
7bb50d2132b47e415d67bd07dcdf4a82ce95fc16
danilocamus/curso-em-video-python
/aula18a.py
327
4.28125
4
pessoas = [['Pedro', 25], ['Maria', 26], ['Jaqueline', 29]] print(pessoas[1]) #mostra a lista de índice 1 que esta dentro da lista pessoas print(pessoas[0][1]) #mostra o conteudo de índice 1 da lista de índice 0 que esta na lista pessoas print(pessoas[0][0]) print(pessoas[1][1]) print(pessoas[2][0]) print(pessoas[2])
false
7bfde9995154ed324c387c2c211583ee1e42cfe9
cuihee/LearnPython
/Day01/c0108.py
471
4.375
4
""" 字典的特点 字典的key和value是什么 新建一个字典 """ # 字典 # 相对于列表,字典的key不仅仅是有序的下标 dict1 = {'one': "我的下标是 one", 2: "我的下标是 2"} print(dict1['one']) # 输出键为 'one' 的值 print(dict1[2]) # 输出键为 2 的值 print('输出所有下标', type(dict1.keys()), dict1.keys()) # 另一种构建方式 dict2 = dict([(1, 2), ('2a', 3), ('3b', 'ff')]) print('第二种构建方式', dict2)
false
59412e27906d5aa3a7f435bfb4ab63d9ee5ed5a2
RamrajSegur/Computer-Vision-Python
/OpenCV-Python/line.py
1,046
4.125
4
#Program to print a line on an image using opencv tools import numpy as np import cv2 # Create a grayscale image or color background of desired intensity img = np.ones((480,520,3),np.uint8) #Creating a 3D array b,g,r=cv2.split(img)#Splitting the color channels img=cv2.merge((10*b,150*g,10*r))#Merging the color channels with modified color channel values # Draw a diagonal blue line with thickness of 5 px print img.dtype print img cv2.line(img,(0,0),(200,250),(0,0,0),5)#First argument defines the image matrix to which the line has to be added #Second and third are coordinate points #Fourth will determine the color of the line which is in matrix form : in BGR Order #Fifth argument gives the width of the line cv2.rectangle(img,(20,30),(300,400),(255,255,255),2) cv2.circle(img,(400,400),40,(0,255,255),4) pts=np.array([[40,50],[80,90],[60,80],[80,90]],np.int32) cv2.polylines(img,[pts],False,(0,0,0),3) font=cv2.FONT_HERSHEY_DUPLEX cv2.putText(img, 'Hello There!',(200,400),font, 1, (200,150,255),2) cv2.imshow('image',img) cv2.waitKey(0)
true
dac4fea633910137cc60dc5c73d8558886877f09
dennisSaadeddin/pythonDataStructures
/manual_queue/Queue.py
2,121
4.15625
4
from manual_queue.QueueElem import MyQueueElement class MyQueue: def __init__(self): self.head = None self.tail = None self.is_empty = True def enqueue(self, elem): tmp = MyQueueElement(elem) if self.head is None: self.head = tmp if self.tail is not None: self.tail.next = tmp self.tail = tmp self.is_empty = False def dequeue(self): if self.is_empty: print("Queue is empty.") else: self.head = self.head.next if self.head is None: self.is_empty = True def front(self): if self.is_empty: print("Queue is empty. There's no front element.") else: print("Head: ", self.head.data) def rear(self): if self.is_empty: print("Queue is empty. There's no rear element.") else: print("Tail: ", self.tail.data) def print_queue(self): tmp = self.head while tmp is not None: if tmp.next is None: print(tmp.data) else: print(tmp.data, " - ", end="", flush=True) tmp = tmp.next breadQueue = MyQueue() breadQueue.enqueue(1) breadQueue.enqueue(2) breadQueue.enqueue(3) breadQueue.enqueue(4) breadQueue.enqueue(5) breadQueue.enqueue(6) breadQueue.enqueue(7) breadQueue.front() breadQueue.rear() if breadQueue.is_empty: print("The queue is empty. Please add elements.") else: print("Here's your queue: ") breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.dequeue() breadQueue.print_queue() breadQueue.front() breadQueue.rear() if breadQueue.is_empty: print("The queue is empty. Please add elements.") else: print("Here's your queue: ", breadQueue.print_queue()) if __name__ == "__main__": MyQueue()
false
c954b3d5067de813172f46d1ce5b610a5adc6317
LL-Pengfei/cpbook-code
/ch2/vector_arraylist.py
421
4.125
4
def main(): arr = [7, 7, 7] # Initial value [7, 7, 7] print("arr[2] = {}".format(arr[2])) # 7 for i in range(3): arr[i] = i; print("arr[2] = {}".format(arr[2])) # 2 # arr[5] = 5; # index out of range error generated as index 5 does not exist # uncomment the line above to see the error arr.append(5) # list will resize itself after appending print("arr[3] = {}".format(arr[3])) # 5 main()
true
039e8c37b1c95e7659c109d2abbef9b697e7ca3d
xiaochenchen-PITT/CC150_Python
/Design_Patterns/Factory.py
2,731
4.78125
5
'''The essence of Factory Design Pattern is to "Define a factory creation method(interface) for creating objects for different classes. And the factory instance is to instantiate other class instances. The Factory method lets a class defer instantiation to subclasses." Key point of Factory Design Pattern is-- Only when inheritance is involved is factory method pattern. ''' class Button(object): """class Button has 3 subclasses Image, Input and Flash.""" def __init__(self): self.string = '' def GetString(self): return self.string class Image(Button): """docstring for Image""" def __init__(self): self.string = 'string for Image.' class Input(Button): """docstring for Input""" def __init__(self): self.string = 'string for Input.' class Flash(Button): """docstring for Flash""" def __init__(self): self.string = 'string for Flash.' class ButtonFactory: """ButtonFactory is the Factory class for Button, its instance is to instantiate other button class instances""" buttons = {'image': Image, 'input': Input, 'flash': Flash} # value is class def create_button(self, typ): return self.buttons[typ]() # () is for instantiating class !!! # eg. s = Solution() button_obj = ButtonFactory() # Factory instance is for instantiating other class for b in button_obj.buttons: print button_obj.create_button(b).GetString() # print button_obj.buttons['image'] # print Flash '''Another example/way for Factory design pattern. Blackjack cards example. ''' class CardFactory: # Factory class def Newcard(self, rank, suit): if rank == 1: return ACE(rank, suit) elif rank in [11, 12, 13]: return FaceCard(rank, suit) else: return Card(rank, suit) class Deck: def __init__(self, ): factory = CardFactory() self.cards = [factory.Newcard(rank + 1, suit) for suit in ['Spade', 'Heart', 'Club', 'Diamond'] for rank in range(13)] # Above is a huge list comprehesive!! class Card: """Base class: Normal card""" def __init__(self, rank, suit): self.rank = rank self.suit = suit self.val = rank def __str__(self): return '{1} {0}'.format(self.rank, self.suit) def GetSoftvalue(self): return self.val def GetHardvalue(self): return self.val class ACE(Card): def __init__(self, rank, suit): Card.__init__(self, rank, suit) def __str__(self): return '{1} {0}'.format('A', self.suit) def GetSoftvalue(self): return 11 def GetHardvalue(self): return 1 class FaceCard(Card): """J, Q, K.""" def __init__(self, rank, suit): Card.__init__(self, rank, suit) self.val = 10 def __str__(self): label = ('J', 'Q', 'K')[self.rank - 11] return '{1} {0}'.format(label, self.suit) deck = Deck() for card in deck.cards: print card
true
6ce064242cb40428e52917203518b1291ceeb0e5
emetowinner/python-challenges
/Phase-1/Python Basic 2/Day-26.py
2,807
4.5625
5
''' 1. Write a Python program to count the number of arguments in a given function. Sample Output: 0 1 2 3 4 1 2. Write a Python program to compute cumulative sum of numbers of a given list. Note: Cumulative sum = sum of itself + all previous numbers in the said list. Sample Output: [10, 30, 60, 100, 150, 210, 217] [1, 3, 6, 10, 15] [0, 1, 3, 6, 10, 15] 3. Write a Python program to find the middle character(s) of a given string. If the length of the string is odd return the middle character and return the middle two characters if the string length is even. Sample Output: th H av 4. Write a Python program to find the largest product of the pair of adjacent elements from a given list of integers. Sample Output: 30 20 6 5. Write a Python program to check whether every even index contains an even number and every odd index contains odd number of a given list. Sample Output: True False True 6. Write a Python program to check whether a given number is a narcissistic number or not. If you are a reader of Greek mythology, then you are probably familiar with Narcissus. He was a hunter of exceptional beauty that he died because he was unable to leave a pool after falling in love with his own reflection. That's why I keep myself away from pools these days (kidding). In mathematics, he has kins by the name of narcissistic numbers - numbers that can't get enough of themselves. In particular, they are numbers that are the sum of their digits when raised to the power of the number of digits. For example, 371 is a narcissistic number; it has three digits, and if we cube each digits 33 + 73 + 13 the sum is 371. Other 3-digit narcissistic numbers are 153 = 13 + 53 + 33 370 = 33 + 73 + 03 407 = 43 + 03 + 73. There are also 4-digit narcissistic numbers, some of which are 1634, 8208, 9474 since 1634 = 14+64+34+44 8208 = 84+24+04+84 9474 = 94+44+74+44 It has been proven that there are only 88 narcissistic numbers (in the decimal system) and that the largest of which is 115,132,219,018,763,992,565,095,597,973,971,522,401 has 39 digits. Ref.: //https://bit.ly/2qNYxo2 Sample Output: True True True False True True True False 7. Write a Python program to find the highest and lowest number from a given string of space separated integers. Sample Output: (77, 0) (0, -77) (0, 0) 8. Write a Python program to check whether a sequence of numbers has an increasing trend or not. Sample Output: True False False True False 9. Write a Python program to find the position of the second occurrence of a given string in another given string. If there is no such string return -1. Sample Output: -1 31 10. Write a Python program to compute the sum of all items of a given array of integers where each integer is multiplied by its index. Return 0 if there is no number. Sample Output: 20 -20 0 '''
true
48449d264326a4508b0f111d19a6f5832155485d
emetowinner/python-challenges
/Phase-1/Python Basic 2/Day-28.py
2,740
4.375
4
''' 1. Write a Python program to check whether two given circles (given center (x,y) and radius) are intersecting. Return true for intersecting otherwise false. Sample Output: True False 2. Write a Python program to compute the digit distance between two integers. The digit distance between two numbers is the absolute value of the difference of those numbers. For example, the distance between 3 and -3 on the number line given by the |3 - (-3) | = |3 + 3 | = 6 units Digit distance of 123 and 256 is Since |1 - 2| + |2 - 5| + |3 - 6| = 1 + 3 + 3 = 7 Sample Output: 7 6 1 11 3. Write a Python program to reverse all the words which have even length. Sample Output: 7 6 1 11 4. Write a Python program to print letters from the English alphabet from a-z and A-Z. Sample Output: Alphabet from a-z: a b c d e f g h i j k l m n o p q r s t u v w x y z Alphabet from A-Z: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 5. Write a Python program to generate and prints a list of numbers from 1 to 10. Sample Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 6. Write a Python program to identify nonprime numbers between 1 to 100 (integers). Print the nonprime numbers. Sample Output: Nonprime numbers between 1 to 100: 4 6 8 9 10 .. 96 98 99 100 7. Write a Python program to make a request to a web page, and test the status code, also display the html code of the specified web page. Sample Output: Web page status: <Response [200]> HTML code of the above web page: <!doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <div> <h1>Example Domain</h1> <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p> <p><a href="https://www.iana.org/domains/example">More information...</a></p> </div> </body> </html> 8. In multiprocessing, processes are spawned by creating a Process object. Write a Python program to show the individual process IDs (parent process, process id etc.) involved. Sample Output: Main line module name: __main__ parent process: 23967 process id: 27986 function f module name: __main__ parent process: 27986 process id: 27987 hello bob 9. Write a Python program to check if two given numbers are coprime or not. Return True if two numbers are coprime otherwise return false. Sample Output: True True False False 10. Write a Python program to calculate Euclid's totient function of a given integer. Use a primitive method to calculate Euclid's totient function. Sample Output: 4 8 20 '''
true
6ece47524c7619b649fd02a684262c06eac17f53
Megha2122000/python3
/3.py
361
4.21875
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 19 15:30:29 2021 @author: Comp """ # Python program to print positive Numbers in a List # list of numbers list1 = [-12 , -7 , 5 ,64 , -14] # iterating each number in list for num in list1: # checking condition if num >= 0: print(num, end = " ")
true
ccad48e6c0098ebc9f19b8218034baada0a18a53
sushrest/machine-learning-intro
/decisiontree.py
1,455
4.4375
4
# scikit-learn Machine Learning Library in python # Environment Python Tensorflow # Following example demonstrates a basic Machine Learning examples using # Supervised Learning by making use of Decision Tree Classifier and its fit algorithm to predict whether the given # features belong to Apple or Orange from sklearn import tree # Preparing data for the decision tree classifier # features as an input for classifier features = [ [140, 1], #140 as weight in grams and 1 as Bumpy surface and 0 as Smooth surface [130, 1], [150, 0], [170, 0] ] # labels as an output for classifier labels = [0, 0, 1, 1] # 0 as an apple and 1 as orange print 'Marking features type to Int by' print '1 as Smooth and 0 as Bumpy and 0 as Apple and 1 as Orange' print ' ' # Initializing a classifier this can be treated as an empty box of Rule. clf = tree.DecisionTreeClassifier() print '.' print '.' print 'Learning algorithm is just a procedure that creates classifier such as DecisionTree.' print '.' print '.' print ' ' print 'Calling a built-in algorithm called fit from DecisionTreeClassifier Object ' print '.' print ' ' print 'Think of fit being a synonym for Fine Pattern and Data' print '.' print ' ' clf = clf.fit(features, labels) print 'Now lets Predict' print '1' print '2.. and ' print 'BAAAM !!' print 'Predicting a fruit which is 160g and Bumpy = 0 ' print clf.predict([[160,0]]) print 'If 0 its Apple and if 1 its Orange'
true
ccc3abda28abe8e4719c043e55fe47fe3e9f7b53
fight741/DaVinciCode
/main.py
435
4.15625
4
import numpy as np start = input("start from : ") end = input("end with : ") number = int(np.random.randint(int(start), int(end)+1)) g = int(input("Input your guess here : ")) while g != number: if g > number: print("The number is smaller") g = int(input("Give another guess : ")) else: print("The number is bigger") g = int(input("Give another guess : ")) print("HOOORAY! That's correct!")
true
ce4538035bd10d46defe36ca39677409fad124a8
AndresMontenegroArguello/UTC
/2020/Logica y Algoritmos/Tareas/Tarea 2/Extras/Python/Tarea 2.1 - Colones.py
626
4.34375
4
# Introducción print("Logica y Algoritmos") print("Andres Montenegro") print("02/Febrero/2020") print("Tarea 2.1") print("Colones") print("**********") # Definición de variables # Python es de tipado dinámico por lo que no es necesario declarar antes de asignar valor a las variables # Ingreso de datos por el usuario print("Ingrese la cantidad de Colones que posee Pepe: ") Pepe = float(input()) # Procesamiento de datos Juan = Pepe / 2 Ana = (Juan + Pepe) / 2 # Presentación de resultados print("Pepe posee " + str(Pepe) + " Colones") print("Juan posee " + str(Juan) + " Colones") print("Ana posee " + str(Ana) + " Colones")
false
8bb4ef10fa5bb4e81806cdb797e2a7d857854f37
mbeliogl/simple_ciphers
/Caesar/caesar.py
2,137
4.375
4
import sys # using caesar cipher to encrypy a string def caesarEncrypt(plainText, numShift): alphabet = 'abcdefghijklmnopqrstuvwxyz ' key = [] cipherText = '' plainText = plainText.lower() # the for loop ensures we are looping around for i in range(len(alphabet)): if i + numShift >= 27: key.append(alphabet[i + numShift - 27]) else: key.append(alphabet[i+numShift]) # shifting each character n spaces for i in range(len(plainText)): cipherText = cipherText + key[alphabet.find(plainText[i])] return cipherText # decrypting the string by reversing the caesarEncrypt() method def caesarDecrypt(cipherText, numberShift): alphabet = 'abcdefghijklmnopqrstuvwxyz ' key = [] plainText = '' for i in range(len(alphabet)): if i + numberShift >= 27: key.append(alphabet[i + numberShift - 27]) else: key.append(alphabet[i + numberShift]) for i in range(len(cipherText)): plainText = plainText + alphabet[key.index(cipherText[i])] return plainText # breaking using brute force approach def caesarBreak(cipherText): guess = 1 for i in range(27): print('Guess ' + str(guess) + ': ' + caesarDecrypt(cipherText, i)) guess = guess + 1 # driver def main(): task_list = ['encrypt', 'decrypt', 'break'] task = input(f"Please choose the task type {task_list} : ") if task == task_list[0]: msg = input("Enter the string to encrypt: ") key = int(input("Enter the key (how many letters to shift): ")) key = key % 27 encrypted_msg = caesarEncrypt(msg, key) print(f"Your encrypted message: {encrypted_msg}") if task == task_list[1]: msg = input("Enter the string to decrypt: ") key = int(input("Enter the key (how many letters to shift): ")) key = key % 27 decrypted_msg = caesarDecrypt(msg, key) print(f"\nYour encrypted message: {decrypted_msg}") if task == task_list[2]: msg = input("Enter the string break: ") caesarBreak(msg) main()
true
4d969849727d7b049825d2dcf47db14b7dd16a67
AndrewBowerman/example_projects
/Python/oopRectangle.py
1,745
4.5625
5
""" oopRectangle.py intro to OOP by building a Rectangle class that demonstrates inheritance and polymorphism. """ def main(): print ("Rectangle a:") a = Rectangle(5, 7) print ("area: {}".format(a.area)) print ("perimeter: {}".format(a.perimeter)) print ("") print ("Rectangle b:") b = Rectangle() b.width = 10 b.height = 20 print (b.getStats()) # start of my code # create a base class with a constructor to inherit into rectangle class class Progenitor(object): def __init__(self, height = 10, width = 10): object.__init__(self) self.setHeight(height) self.setWidth(width) # lets get down to business # to defeat the huns class Rectangle(Progenitor): #METHODS #constructor is imported from progenitor #setters for width and height def setWidth (self, width): self.__width = width def setHeight (self, height): self.__height = height def setArea (self): return getArea() # getters return area and perimeter def getArea (self): return (self.__height * self.__width) def getPerimeter (self): return ((self.__height + self.__width) * 2) # getter for all rectangle stats def getStats (self): print("width: {}".format(self.__width)) print("height: {}".format(self.__height)) print("area: {}".format(self.__area)) print("perimeter: {}".format(perimeter)) #ATTRIBUTES width = property(fset = setWidth) height = property(fset = setHeight) area = property(fset = setArea, fget = getArea) perimeter = property(fget = getPerimeter) main()
true
6f7d33585fac28efdcbd848c65e489bb71044b0b
singhankur7/Python
/advanced loops.py
2,306
4.375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 9 23:48:15 2019 @author: New """ """ Python is easy: Homework assignment #6 Advanced Loops """ # for the maximum width(columns) and maximum height(rows) that my playing board can take # This was achieved by trial and error # Defining the function which takes two inputs - rows and columns def playingBoard(rows,columns): if rows<=15 and columns<=15: #declaring the number of rows and columns for r in range(1,rows): #loop for the rows if r % 2 == 0: #checking the rows if it is even or not for c in range(1,columns): #loop for the columns if c % 2 == 1: #checking the columns for odd print(" ",end=" ") #printing for even row and odd column else: print("$$",end=" ") #printing for even row and even column else: for c in range(1,columns): if c % 2 == 1: print("$$",end=" ") #printing for odd row and odd column else: print(" ",end=" ") #printing for odd row and even column print(" ") return True else: return False op = playingBoard(6,8) #calling the function and passing the value if op == True: print("True : playing board is created successfully") else: print("False : number of rows and columns exceeds the limit") print(" ") print("check maximum width and height of playing board") print(" ") op = playingBoard(11,14) #calling the function and passing the value if op == True: print("True : playing board is created successfully") else: print("False : number of rows and columns exceeds the limit") print(" ") print("check maximum width and height of playing board") print(" ") op = playingBoard(16,18) #calling the function and passing the value if op == True: print("True : playing board is created successfully") else: print("False : number of rows and columns exceeds the limit")
true
b6b9a578c524fa372d4adf93096d3a5c29b5c5d0
sagarneeli/coding-challenges
/Linked List/evaluate_expression.py
2,583
4.59375
5
# Python3 program to evaluate a given # expression where tokens are # separated by space. # Function to find precedence # of operators. def precedence(op): if op == '+' or op == '-': return 1 if op == '*' or op == '/': return 2 return 0 # Function to perform arithmetic # operations. def applyOp(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': return a // b # Function that returns value of # expression after evaluation. def evaluate(tokens): # stack to store integer values. values = [] # stack to store operators. ops = [] i = 0 while i < len(tokens): # Current token is a whitespace, # skip it. if tokens[i] == ' ': i += 1 continue # Current token is an opening # brace, push it to 'ops' elif tokens[i] == '(': ops.append(tokens[i]) # Current token is a number, push # it to stack for numbers. elif tokens[i].isdigit(): val = 0 # There may be more than one # digits in the number. while (i < len(tokens) and tokens[i].isdigit()): val = (val * 10) + int(tokens[i]) i += 1 values.append(val) # Closing brace encountered, # solve entire brace. elif tokens[i] == ')': while len(ops) != 0 and ops[-1] != '(': val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # pop opening brace. ops.pop() # Current token is an operator. else: # While top of 'ops' has same or # greater precedence to current # token, which is an operator. # Apply operator on top of 'ops' # to top two elements in values stack. while (len(ops) != 0 and precedence(ops[-1]) >= precedence(tokens[i])): val2 = values.pop() val1 = values.pop() op = ops.pop() values.append(applyOp(val1, val2, op)) # Push current token to 'ops'. ops.append(tokens[i]) i += 1 # Entire expression has been parsed # at this point, apply remaining ops # to remaining values. print(values) print(ops) while len(ops) != 0: val2 = values.pop() val1 = values.pop() op = ops.pop() print(val2) print(val1) print(ops) values.append(applyOp(val1, val2, op)) # Top of 'values' contains result, # return it. return values[-1] # Driver Code # print(evaluate("10 + 2 * 6")) # print(evaluate("100 * 2 + 12")) print(evaluate("(1+(4+5+2)-3)+(6+8)")) # print(evaluate("3 + 2 * 2")) # This code is contributed # by Rituraj Jain
true
0a1a0f66af66feb4ee13899192bc64ef2d66f018
sy-li/ICB_EX7
/ex7_sli.py
1,791
4.375
4
# This script is for Exercise 7 by Shuyue Li # Q1 import pandas as pd def odd(df): ''' This function is aimed to return the add rows of a pandas dataframe df should be a pandas dataframe ''' nrow = df.shape[0] odds = pd.DataFrame() for i in range(1,nrow): if i%2 == 0: continue else: odds = odds.append(df.iloc[i,:]) return odds # test data iris = pd.read_csv("iris.csv", delimiter = ",") print odd(iris) # Q2 def ct_sp(data,species): ''' This function is aimed to return the number of observations for a given species included in the data set data should be a pandas dataframe; species should be a string ''' sp = data.loc[data['Species']==species] return sp.shape[0] # test data iris = pd.read_csv("iris.csv", delimiter = ",") print ct_sp(iris,"setosa") def select_sepal(data,width): ''' This function is used to return a dataframe for flowers with Sepal.Width greater than a value specified by the function user data is a pandas dataframe; width is specified width ''' if width > data["Sepal.Width"].max(): print "Invalid value: larger than maximum width" else: select = data.loc[data['Sepal.Width'] > width] return select # test data iris = pd.read_csv("iris.csv", delimiter = ",") print select_sepal(iris,3.5) def extract_species(data,species): ''' This function is used to select a given species and save to a csv file data should be a pandas dataframe; species should be a string ''' sp = data.loc[data['Species']==species] file_name = str(species) + ".csv" sp.to_csv(file_name, sep=',') # test data iris = pd.read_csv("iris.csv", delimiter = ",") extract_species(iris,"setosa")
true
c24b76b40773bcde6356d5ba2f951cdd3eea5d94
io-ma/Zed-Shaw-s-books
/lmpthw/ex4_args/sys_argv.py
1,302
4.4375
4
""" This is a program that encodes any text using the ROT13 cipher. You need 2 files in the same dir with this script: text.txt and result.txt. Write your text in text.txt, run the script and you will get the encoded version in result.txt. Usage: sys_argv.py -i <text.txt> -o <result.txt> """ import sys, codecs for arg in sys.argv[1:]: arg_pos = sys.argv[1:].index(arg) + 1 if arg in ["-h", "--help", "-i", "--input", "-o", "--output"]: if arg == "-h" or arg == "--help": v = __doc__ print(v) elif arg == "-i" or arg == "--input": ifile = sys.argv[arg_pos + 1] text = ifile elif arg == "-o" or arg == "--output": ofile = sys.argv[arg_pos +1] result = ofile else: print("""You need an input and an output file. Type -h for more info.""") class Encode(object): def encode_txt(self): """ This function encodes the text """ txt = open(text) read = txt.read() encoded = codecs.encode(read, 'rot_13') target = open(result, 'w') target.write(encoded) target.close() def main(): encode = Encode() encode.encode_txt() print("Succes! Your file is encoded.") if __name__ == "__main__": main()
true
e015f0925ccb831ef32e805bd81fff3db46668f6
io-ma/Zed-Shaw-s-books
/lpthw/ex19/ex19_sd1.py
1,485
4.34375
4
# define a function called cheese_and_crackers that takes # cheese_count and boxes_of_crackers as arguments def cheese_and_crackers(cheese_count, boxes_of_crackers): # prints a string that has cheese_count in it print(f"You have {cheese_count} cheeses!") # prints a string that has boxes_of_crackers in it print(f"You have {boxes_of_crackers} boxes of crackers!") # prints a string print("Man that's enough for a party!") # prints a string and a newline print("Get a blanket.\n") # prints we can give the function numbers directly print("We can just give the function numbers directly:") # gives cheese_and_crackers function 20 and 30 as arguments and calls it cheese_and_crackers(20, 30) # prints we can use variables as arguments print("OR, we can use variables from our script:") # assigns 10 to a variable amount_of_cheese amount_of_cheese = 10 # assigns 50 to a variable amount_of_crackers amount_of_crackers = 50 # calls cheese_and_crackers function with variables as arguments cheese_and_crackers(amount_of_cheese, amount_of_crackers) # prints we can have math inside too print("We can even do math inside too:") # calls cheese_and_crackers giving it math as arguments cheese_and_crackers(10 + 20, 5 + 6) # prints we can combine variables and math print("And we can combine the two, variables and math:") # calls cheese_and_crackers with variables and math as arguments cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
true
a6da253639d8ca65b62444ec6bc60545c11d2501
blakfeld/Data-Structures-and-Algoritms-Practice
/Python/general/binary_search_rotated_array.py
1,661
4.34375
4
#!/usr/bin/env python """ binary_search_rotated_array.py Author: Corwin Brown <blakfeld@gmail.com> """ from __future__ import print_function import sys import utils def binary_search(list_to_search, num_to_find): """ Perform a Binary Search on a rotated array of ints. Args: list_to_search (list): The list to search. num_to_find (int): The int to search for. Returns: tuple: (index, value) """ first = 0 last = len(list_to_search) - 1 while first <= last: mid = (first + last) // 2 if list_to_search[mid] == num_to_find: return mid, list_to_search[mid] # Is first half sorted? if list_to_search[first] <= list_to_search[mid]: # If first and mid are less than num_to_find, Search the # first half, else search the second half. if all([list_to_search[first] <= num_to_find, list_to_search[mid] >= num_to_find]): last = mid - 1 else: first = mid + 1 # If the second half is sorted. else: # If last and mid are less than num_to_find, Search the # second half, else search the first half. if all([list_to_search[mid] <= num_to_find, list_to_search[last] <= num_to_find]): first = mid + 1 else: last = mid - 1 return None, None def main(): """ Main. """ list_to_search = utils.rotate_list(sorted(utils.get_unique_random_list()), 10) print(binary_search(list_to_search, 30)) if __name__ == '__main__': sys.exit(main())
true
c6b2dab45e102ae19dc887e97e296e5c90f68a51
tocxu/program
/python/function_docstring.py
264
4.34375
4
def print_max(x,y): '''Prints the maximum of two numbers. The two values must be integers.''' #convert to integers, if possible x=int(x) y=int(y) if x>y: print x, 'is maximum' else: print y,'is maximum' print (3,5) print_max(3,5) print print_max.__doc__
true
0939ff340b6f0410cedac5b9966dc13d0e42269d
yaelh1995/AlumniPythonClass
/ex18.py
592
4.15625
4
'''def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}" def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothin'.") print_two("Zed","Shaw")''' '''def function(x, y, z): answer = (x + y + z) / 3 print(f""" The sum of all three numbers divided by three is {answer}.""") function(1, 2, 3)''' def function(x, y, z): sum = (x + y + z) print(f"The sum is {sum}.") function(19, -8, 9) function(15, 9, 8) function(30, -29, 5)
false
684c0c1dda56869fc93817a64f67acb1606107a2
humbertoperdomo/practices
/python/PythonPlayground/PartI/Chapter02/draw_circle.py
455
4.4375
4
#!/usr/bin/python3 # draw_circle.py """Draw a circle """ import math import turtle def draw_circle_turtle(x, y, r): """Draw the circle using turtle """ # move to the start of circle turtle.up() turtle.setpos(x + r, y) turtle.down() # draw the circle for i in range(0, 361, 1): a = math.radians(i) turtle.setpos(x + r * math.cos(a), y + r * math.sin(a)) draw_circle_turtle(100, 100, 50) turtle.mainloop()
false
a4b203896d017258eb8d703b4afc92ce8d03df7c
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter09/number_served.py
1,550
4.15625
4
#!e/urs/bn/python3 # restaurant.py """Class Restaurant""" class Restaurant(): """Class that represent a restaurant.""" def __init__(self, restaurant_name, cuisine_type): """Initialize restaurant_name and cuisine_type attributes.""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurat(self): """Describes restaurant using both attributes.""" print(self.restaurant_name.title() + " is a restaurant of " + self.cuisine_type + " food.") def open_restaurant(self): """Simulates that restaurant is open.""" print(self.restaurant_name.title() + " is open.") def set_number_served(self, number_served): """Set the number of customers served.""" self.number_served = number_served def increment_number_served(self, served): """Increment the customers served using served amount.""" self.number_served += served RESTAURANT = Restaurant("alessandro's", 'italian') print("Restaurant name: " + RESTAURANT.restaurant_name.title() + ".") print("Cuisine type: " + RESTAURANT.cuisine_type + ".") RESTAURANT.describe_restaurat() RESTAURANT.open_restaurant() print("Customer the restaurant has served: " + str(RESTAURANT.number_served)) RESTAURANT.set_number_served(7) print("Customer the restaurant has served: " + str(RESTAURANT.number_served)) RESTAURANT.increment_number_served(5) print("Customer the restaurant has served: " + str(RESTAURANT.number_served))
true
6824e7c7d9116fc808d6320f206dd5845e6b0ba5
guguda1986/python100-
/例8.py
351
4.1875
4
#例8:输出99乘法表 for x in range(0,10): for y in range(0,10): if x==0: if y==0: print("*",end="\t") else: print(y,end="\t") else: if y==0: print(x,end="\t") else: print(x*y,end="\t") print("\n")
false
5d2c49f3e11cc346105c7fb02c59435e2b56af76
Necmttn/learning
/python/algorithms-in-python/r-1/main/twenty.py
790
4.25
4
""" Python’s random module includes a function shuffle(data) that accepts a list of elements and randomly reorders the elements so that each possi- ble order occurs with equal probability. The random module includes a more basic function randint(a, b) that returns a uniformly random integer from a to b (including both endpoints). Using only the randint function, implement your own version of the shuffle function. """ import random array = [1,2,3,5,6,7,8,9,0] # random.shuffle(array) # print(array) def everyday_shuffling(arr): for n in range(len(arr)): random_index = random.randint(0, n) tmp = arr[random_index] arr[random_index] = arr[n] arr[n] = tmp return arr print(len(array)) everyday_shuffling(array) print(array) print(len(array))
true
d69ba19f1271f93a702fd8009c57a34a11122c6b
Necmttn/learning
/python/algorithms-in-python/r-1/main/sixteen.py
684
4.21875
4
""" In our implementation of the scale function (page25),the body of the loop executes the command data[j]= factor. We have discussed that numeric types are immutable, and that use of the *= operator in this context causes the creation of a new instance (not the mutation of an existing instance). How is it still possible, then, that our implementation of scale changes the actual parameter sent by the caller? """ #the function which is at (page25) def scale(data, factor): #for j in range(len(data)): # arr[j] *= factor for k in data: k *= factor print k return data array = [1,2,3,4,5,6] array2 = scale(array, 3) print array print array
true
8cc73de7110d0300d84909f76d7cebb6f0e772e9
tboy4all/Python-Files
/csv_exe.py
684
4.1875
4
#one that prints out all of the first and last names in the users.csv file #one that prompts us to enter a first and last name and adds it to the users.csv file. import csv # Part 2 def print_names(): with open('users.csv') as file: reader = csv.DictReader(file) for row in reader: print("{} {}".format(row['first_name'], row['last_name'])) def add_name(): with open('users.csv', 'a') as file: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(file, fieldnames) first = input("First name please: ") last = input("Last name please: ") writer.writerow(dict(first_name=first, last_name=last))
true
0fbfcaafa9794d32855c67db1117c3ec4d682864
holomorphicsean/PyCharmProjectEuler
/euler9.py
778
4.28125
4
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2 + b**2 = c**2 For example, 3**2 + 4**2 = 9 + 16 = 2**5 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.""" import time import math # We are going to just brute force this and check all combinations # until we come across our answer t0 = time.time() for a in range(1,1000+1): for b in range(a,1000+1): c = math.sqrt(a**2 + b**2) # if c is not an integer forget it if c != int(c): continue # now we check if we hit the special triplet if a + b + c == 1000: print(int(a*b*c)) break t1 = time.time() print("Execution time: " + str(t1 - t0) + " seconds.")
true
1dbf066eeb432496cb1cc5dec86d41f54eefd74f
Murali1125/Fellowship_programs
/DataStructurePrograms/2Darray_range(0,1000).py
901
4.15625
4
"""-------------------------------------------------------------------- -->Take a range of 0 - 1000 Numbers and find the Prime numbers in that --range. Store the prime numbers in a 2D Array, the first dimension --represents the range 0-100, 100-200, and so on. While the second --dimension represents the prime numbers in that range --------------------------------------------------------------------""" from Fellowship_programs.DataStructurePrograms.Array2D import prime print("range is 0 to 1000") # creating object for array2D class obj = prime() # declare a iterator variable to count the loop iterations itr = 0 # creating an empty list to store the prime numbers in the given range list = [] for i in range(0,1000,100): # calling the prime function to get the prime numbers lis = obj.prime(i,i+100) itr +=1 list.append(lis) # printing the 2d prime number array obj.Print(itr)
true
ebfd35ab13d1b55fe3b78f1974a512a1dccb7a4d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/921 Minimum Add to Make Parentheses Valid.py
1,116
4.21875
4
#!/usr/bin/python3 """ Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid. Example 1: Input: "())" Output: 1 Example 2: Input: "(((" Output: 3 Example 3: Input: "()" Output: 0 Example 4: Input: "()))((" Output: 4 Note: S.length <= 1000 S only consists of '(' and ')' characters. """ c_ Solution: ___ minAddToMakeValid S: s..) __ i.. """ stk """ ret 0 stk # list ___ s __ S: __ s __ "(": stk.a..(s) ____ __ stk: stk.p.. ) ____ ret += 1 ret += l..(stk) r.. ret
true
3e60a45e7923bb72bece7ee0f705b2d6467ee4a6
syurskyi/Python_Topics
/070_oop/001_classes/examples/The_Complete_Python_Course_l_Learn_Python_by_Doing/61. More about classes and objects.py
1,239
4.5
4
""" Object oriented programming is used to help conceptualise the interactions between objects. I wanted to give you a couple more examples of classes, and try to answer a few frequent questions. """ class Movie: def __init__(self, name, year): self.name = name self.year = year """ Parameter names (in `(self, name, year)`) hold the values of the arguments that we were given when the method was called: `Movie(‘The Matrix’, 1994)`. `self.name` and `self.year` are the names of the properties of the new object we are creating. They only exist within the `self` object, so it’s totally OK to have `self.name = name`. """ ## `self` ? """ It’s common in Python to call the “current object” `self`. But it doesn’t have to be that way! """ class Movie: def __init__(current_object, name, year): current_object.name = name current_object.year = year """ Don’t do this, for it will look very weird when someone reads your code (e.g. if you work or go to an interview), but just remember that `self` is like any other variable name— it can be anything you want. `self` is just the convention. Many editors will syntax highlight it differently because it is so common. """
true
bbbd1d21e8e907c7353f2a1aee9c6c2984a4c255
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Algorithmic Problems in Python/binary_search.py
986
4.3125
4
#we can achieve O(logN) but the array must be sorted ___ binary_search(array,item,left,right): #base case for recursive function calls #this is the search miss (array does not contain the item) __ right < left: r.. -1 #let's generate the middle item's index middle left + (right-left)//2 print("Middle index: ",middle) #the middle item is the item we are looking for __ array[middle] __ item: r.. middle #the item we are looking for is smaller than the middle item #so we have to consider the left subarray ____ array[middle] > item: print("Checking items on the left...") r.. binary_search(array,item,left,middle-1) #the item we are looking for is greater than the middle item #so we have to consider the right subarray ____ array[middle] < item: print("Checking items on the right...") r.. binary_search(array,item,middle+1,right) __ _______ __ _______ array [1,4,7,8,9,10,11,20,22,25] print(binary_search(array,111,0,l..(array)-1))
true
5fb93b463f49e0440570a02f3d1eea4cc91e8d0f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/405 Convert a Number to Hexadecimal.py
1,467
4.3125
4
""" Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two's complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. The given number is guaranteed to fit within the range of a 32-bit signed integer. You must not use any method provided by the library which converts/formats the number to hex directly. Example 1: Input: 26 Output: "1a" Example 2: Input: -1 Output: "ffffffff" """ __author__ 'Daniel' c_ Solution(o.. ___ toHex num """ All use bit manipulation :type num: int :rtype: str """ ret # list w.... l..(ret) < 8 a.. num: ret.a..(encode(num & 0xf num >>= 4 r.. ''.j..(ret||-1]) o. '0' ___ toHexNormal num """ Python arithmetic handles the negative number very well :type num: int :rtype: str """ ret # list w.... l..(ret) < 8 a.. num: ret.a..(encode(num % 16 num /= 16 r.. ''.j..(ret||-1]) o. '0' ___ encode d __ 0 <_ d < 10: r.. s..(d) r.. chr(o..('a') + d - 10) __ _______ __ _______ ... Solution().toHex(-1) __ 'ffffffff'
true
e415830c017fb802d0f55c1f525d59af43fe82b1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/838 Push Dominoes.py
2,392
4.1875
4
#!/usr/bin/python3 """ There are N dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed. Return a string representing the final state. Example 1: Input: ".L.R...LR..L.." Output: "LL.RR.LLRRLL.." Example 2: Input: "RR.L" Output: "RR.L" Explanation: The first domino expends no additional force on the second domino. Note: 0 <= N <= 10^5 String dominoes contains only 'L', 'R' and '.' """ c_ Solution: ___ pushDominoes dominoes: s..) __ s.. """ DP L & R from both ends Let L[i] be the distance to the "L" from the right we will consider that a falling domino expends no additional force """ n l..(dominoes) L [f__("inf") ___ i __ r..(n)] R [f__("inf") ___ i __ r..(n)] ___ i __ r..(n-1, -1, -1 __ dominoes[i] __ "L": L[i] 0 ____ dominoes[i] __ "R": L[i] f__("inf") ____ i + 1 < n: L[i] L[i+1] + 1 ___ i __ r..(n __ dominoes[i] __ "R": R[i] 0 ____ dominoes[i] __ "L": R[i] f__("inf") ____ i - 1 >_ 0: R[i] R[i-1] + 1 ret # list ___ i __ r..(n d m..(R[i], L[i]) __ d __ f__("inf" cur "." ____ R[i] __ L[i]: cur "." ____ d __ R[i]: cur "R" ____ cur "L" ret.a..(cur) r.. "".j..(ret) __ _______ __ _______ ... Solution().pushDominoes(".L.R...LR..L..") __ "LL.RR.LLRRLL.."
true
cf7895c32a09b5ad12e8985b811797f8d3962c58
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/590 N-ary Tree Postorder Traversal.py
1,316
4.1875
4
#!/usr/bin/python3 """ Given an n-ary tree, return the postorder traversal of its nodes' values. For example, given a 3-ary tree: Return its postorder traversal as: [5,6,3,2,4,1]. Note: Recursive solution is trivial, could you do it iteratively? """ # Definition for a Node. c_ Node: ___ - , val, children val val children children ____ t___ _______ L.. ____ c.. _______ d.. c_ Solution: ___ postorder root: 'Node') __ L.. i.. """ maintain a stack, pop and reverse """ __ n.. root: r.. # list ret d..() stk [root] visited s..() w.... stk: cur stk.p.. ) ret.appendleft(cur.val) ___ c __ cur.children: stk.a..(c) r.. l..(ret) ___ postorder_visited root: 'Node') __ L.. i.. """ maintain a stack, if visited before, then pop """ ret # list __ n.. root: r.. ret stk [root] visited s..() w.... stk: cur stk[-1] __ cur __ visited: stk.p.. ) ret.a..(cur.val) ____ visited.add(cur) ___ c __ r..(cur.children stk.a..(c) r.. ret
false
56992da99dfce4fc45484256df0a63cb6f2d082a
syurskyi/Python_Topics
/045_functions/007_lambda/examples/004_Closures.py
613
4.40625
4
# -*- coding: utf-8 -*- def outer_func(x): y = 4 def inner_func(z): print(f"x = {x}, y = {y}, z = {z}") return x + y + z return inner_func for i in range(3): closure = outer_func(i) print(f"closure({i+5}) = {closure(i+5)}") # Точно так же лямбда также может быть замыканием. Вот тот же пример с лямбда-функцией Python: print('#' * 52 + ' ') def outer_func(x): y = 4 return lambda z: x + y + z for i in range(3): closure = outer_func(i) print(f"closure({i+5}) = {closure(i+5)}")
false
d3e9bd61135b603f1f8b149781f49b88e49eb11f
syurskyi/Python_Topics
/030_control_flow/001_if/examples/Python 3 Most Nessesary/4.2. Listing 4.2. Check several conditions.py
790
4.21875
4
# -*- coding: utf-8 -*- print("""Какой операционной системой вы пользуетесь? 1 — Windows 8 2 — Windows 7 3 — Windows Vista 4 — Windows XP 5 — Другая""") os = input("Введите число, соответствующее ответу: ") if os == "1": print("Вы выбрали: Windows 8") elif os == "2": print("Вы выбрали: Windows 7") elif os == "3": print("Вы выбрали: Windows Vista") elif os == "4": print("Вы выбрали: Windows XP") elif os == "5": print("Вы выбрали: другая") elif not os: print("Вы не ввели число") else: print("Мы не смогли определить вашу операционную систему") input()
false
e9e455eacdb596a36f52fee4dd8175aa37686023
syurskyi/Python_Topics
/030_control_flow/example/Python-from-Zero-to-Hero/03-Коллеции, циклы, логика/11_ДЗ-1-2_solution.py
259
4.125
4
# 1 rows = int(input('Enter the number of rows')) for x in range(rows): print('*' * (x+1)) # 2 limit = int(input('Enter the limit')) for x in range(limit): if x % 2 == 0: print(f'{x} is EVEN') else print(f'{x} is ODD')
true
d83552fae236deecb6b23fb25234bdf7ff6f26b9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/771 Jewels and Stones.py
763
4.1875
4
#!/usr/bin/python3 """ You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3 Example 2: Input: J = "z", S = "ZZ" Output: 0 """ c_ Solution: ___ numJewelsInStones J: s.., S: s..) __ i.. """ hash map """ targets s..(J) ret 0 ___ c __ S: __ c __ targets: ret += 1 r.. ret
true
e9b7e415a19e4aae056651b649a4744fe88aba1b
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/693 Binary Number with Alternating Bits.py
729
4.34375
4
#!/usr/bin/python3 """ Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. """ c_ Solution: ___ hasAlternatingBits n: i.. __ b.. last N.. w.... n: cur n & 1 # `if last` is error __ last __ n.. N.. a.. last ^ cur __ 0: r.. F.. last cur n >>= 1 r.. T.. __ _______ __ _______ ... Solution().hasAlternatingBits(5) __ T.. ... Solution().hasAlternatingBits(7) __ F..
true
6c27ed30f7c0259092479eae4b54a924d55e3251
syurskyi/Python_Topics
/045_functions/_examples/Python-from-Zero-to-Hero/04-Функции и модули/06-Decorators.py
1,179
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def hello_world(): print('Hello, world!') hello_world() # In[ ]: hello2 = hello_world hello2() # In[ ]: #return func from func #pass in a func as an arg # In[ ]: def log_decorator(func): def wrap(): print(f'Calling func {func}') func() print(f'Func {func} finished its work') return wrap # In[ ]: def hello(): print('hello, world!') # In[ ]: wrapped_by_logger = log_decorator(hello) wrapped_by_logger() # In[ ]: @log_decorator def hello(): print('hello, world!') # In[ ]: hello() # In[ ]: #decorators are used by frameworks extensively, that's why it's important to understand what they are in essence # In[ ]: from timeit import default_timer as timer import math import time def measure_exectime(func): def inner(*args, **kwargs): start = timer() func(*args, **kwargs) end = timer() print(f'Function {func.__name__} took {end-start} for execution') return inner @measure_exectime def factorial(num): time.sleep(3) print(math.factorial(num)) # In[ ]: factorial(100)
false
550e085e7618bbc1b7046419f23a47587965a162
syurskyi/Python_Topics
/070_oop/004_inheritance/examples/super/Python 3 super()/001_super function example.py
1,476
4.78125
5
# At first, just look at the following code we used in our Python Inheritance tutorial. In that example code, # the superclass was Person and the subclass was Student. So the code is shown below. class Person: # initializing the variables name = "" age = 0 # defining constructor def __init__(self, person_name, person_age): self.name = person_name self.age = person_age # defining class methods def show_name(self): print(self.name) def show_age(self): print(self.age) # # definition of subclass starts here class Student(Person): studentId = "" def __init__(self, student_name, student_age, student_id): Person.__init__(self, student_name, student_age) self.studentId = student_id def get_id(self): return self.studentId # returns the value of student id # # end of subclass definition # # # # Create an object of the superclass person1 = Person("Richard", 23) # # call member methods of the objects person1.show_age() # # Create an object of the subclass student1 = Student("Max", 22, "102") print(student1.get_id()) student1.show_name() # In the above example, we have called parent class function as: # Person.__init__(self, student_name, student_age) # We can replace this with python super function call as below. # # # super().__init__(student_name, student_age) # The output will remain the same in both the cases, as shown in the below image.
true
67592f055428cf2fd1aefd14a535c9d855a5a881
syurskyi/Python_Topics
/010_strings/_exercises/_templates/Python 3 Most Nessesary/6.3. Row operations.py
2,523
4.15625
4
# # -*- coding: utf-8 -*- # f__ -f _______ p.... # for Python 2.7 # # s = "Python" # print(s[0], s[1], s[2], s[3], s[4], s[5]) # # ('P', 'y', 't', 'h', 'o', 'n') # # # s = "Python" # # s[10] # """ # Traceback (most recent call last): # File "<pyshell#90>", line 1, in <module> # s[10] # IndexError: string index out of range # """ # # # s = "Python" # print ? -1 ? le. ?-1 # # ('n', 'n') # # # s = "Python" # # s[0] = "J" # Изменить строку нельзя # """ # Traceback (most recent call last): # File "<pyshell#94>", line 1, in <module> # s[0] = "J" # Изменить строку нельзя # TypeError: 'str' object does not support item assignment # """ # # s = "Python" # # # print ? # Возвращается фрагмент от позиции 0 до конца строки # # 'Python' # # # print ? ? # Указываем отрицательное значение в параметре <Шаг> # # 'nohtyP' # # # print "J" + ? ? # Извлекаем фрагмент от символа 1 до конца строки # # 'Jython' # # # print ? ? # Возвращается фрагмент от 0 до len(s)-1 # # 'Pytho' # # # print ? ? ? # Символ с индексом 1 не входит в диапазон # # 'P' # # print ? ?; # Получаем фрагмент от len(s)-1 до конца строки # # 'n' # # # print ? ? ? # Возвращаются символы с индексами 2, 3 и 4 # # 'tho' # # # print(le. "Python"), le. "\r\n\t"), le. _"\r\n\t" # # (6, 3, 6) # # # s = "Python" # ___ i __ ra.. le. ? print ?? e.._" ") # # # s = "Python" # ___ i __ ? print ? e.._" ") # # # print("Строка1" + "Строка2") # # Строка1Строка2 # # # print("Строка1" "Строка2") # # Строка1Строка2 # # # s = "Строка1", "Строка2" # print(type(s)) # Получаем кортеж, а не строку # # <class 'tuple'> # # # s = "Строка1" # print(s + "Строка2") # Нормально # # Строка1Строка2 # # print(s "Строка2") # Ошибка # # SyntaxError: invalid syntax # # # print("string" + str(10)) # # 'string10' # # # print("-" * 20) # '--------------------' # print("yt" __ "Python") # Найдено # # True # print("yt" __ "Perl") # Не найдено # # False # print("PHP" ___ __ "Python") # Не найдено # # True
false
eb10863faaab3eabc8f28a687d4d698567c8cea0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/149/solution.py
560
4.125
4
words = ("It's almost Holidays and PyBites wishes You a " "Merry Christmas and a Happy 2019").split() def sort_words_case_insensitively(words): """Sort the provided word list ignoring case, and numbers last (1995, 19ab = numbers / Happy, happy4you = strings, hence for numbers you only need to check the first char of the word) """ # this works because: >>> sorted([True, False]) # [False, True] return sorted(words, key=lambda x: (str(x).lower(), x[0].isdigit() )) print(sort_words_case_insensitively(words))
true
167776832ada38867f57a79bd37cf80b5ef2ff70
syurskyi/Python_Topics
/050_iterations_comprehension_generations/001_iterations_and_iteration_tool/examples/013_Copying an Iterator.py
1,344
4.90625
5
# "Copying" an Iterator # Sometimes we may have an iterator that we want to use multiple times for some reason. # As we saw, iterators get exhausted, so # simply making multiple references to the same iterator will not work - # they will just point to the same iterator object. # # What we would really like is a way to "copy" an iterator and use these copies independently of each other. # # As you can see iters is a tuple contains 3 iterators - let's put them into some variables and see what each one is: from itertools import tee def squares(n): for i in range(n): yield i**2 gen = squares(10) gen iters = tee(squares(10), 3) iters iter1, iter2, iter3 = iters next(iter1), next(iter1), next(iter1) next(iter2), next(iter2) next(iter3) # "Copying" an Iterator # As you can see, iter1, iter2, and iter3 are essentially three independent "copies" of our original # iterator (squares(10)) # Note that this works for any iterable, so even sequence types such as lists: # But you'll notice that the elements of lists are not lists themselves! # # As you can see, the elements returned by tee are actually iterators - # even if we used an iterable such as a list to start off with! l = [1, 2, 3, 4] lists = tee(l, 2) lists[0] lists[1] list(lists[0]) list(lists[0]) lists[1] is lists[1].__iter__() '__next__' in dir(lists[1])
true
82432656d06b812015a3cb455c5c05085c762933
syurskyi/Python_Topics
/125_algorithms/005_searching_and_sorting/_exercises/templates/02_Binary Search/4 Binary Search/Binary-Search-Recursive-Implementation-with-Print-Statements.py
1,170
4.25
4
# ___ binary_search data low high item # # print("\n===> Calling Binary Search") # print("Lower bound:" ? # print("Upper bound:" ? # # __ ? <_ ? # middle _ ? + ?//2 # print("Middle index:" ? # print("Item at middle index:" ?|? # print("We are looking for:" ? # print("Is this the item?", "Yes" __ ?|? __ i.. ____ "No" # __ ?|? __ ? # print("The item was found at index:" ? # r_ ? # ____ ?|? > ? # print("The current item is greater than the target item:" ?|? ">" ? # print("We need to discard the upper half of the list" # print("The lower bound remains at:" ? # print("The upper bound is now:" ? - 1 # r_ ? d.. ? m.. - 1 i.. # ____ # print("The current item is smaller than the target item:" ?|? "<" ? # print("We need to discard the lower half of the list") # print("The lower bound is now:" ? + 1 # print("The upper bound remains at:" ? # r_ ? d.. m.. + 1 ? i.. # ____ # print("The item was not found in the list") # r_ -1
false
ff244299c6831f01e62b6e1ec05c777c9840c057
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/197/mday.py
618
4.28125
4
from datetime import date def get_mothers_day_date(year): """Given the passed in year int, return the date Mother's Day is celebrated assuming it's the 2nd Sunday of May.""" day_counter = 1 mothers_day = date(year, 5, day_counter) sunday_count = 0 while sunday_count < 2: if mothers_day.weekday() == 6: sunday_count += 1 day_counter += 1 else: day_counter += 1 if sunday_count == 2: break mothers_day = mothers_day.replace(day=day_counter) return mothers_day # if __name__ == "__main__": # print(get_mothers_day_date(2014))
false
0c8fc8a50961f4cd18c3b1bfe27baf3beb6e8cdc
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/SortArrayByParity.py
889
4.125
4
""" Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Note: 1 <= A.length <= 5000 0 <= A[i] <= 5000 开胃菜,偶数放一堆,奇数放一堆。 O(n). 测试链接: https://leetcode.com/contest/weekly-contest-102/problems/sort-array-by-parity/ contest. """ c.. Solution o.. ___ sortArrayByParity A """ :type A: List[int] :rtype: List[int] """ even # list odd # list ___ i __ A: __ i % 2 __ 0: even.a.. i) ____ odd.a.. i) r_ even + odd
true
9823abdc5913bf193054f16ca7a44b5d55f69d99
syurskyi/Python_Topics
/070_oop/008_metaprogramming/examples/Expert Python Programming/properties_decorator.py
1,167
4.53125
5
""" "Properties" section example of writing properties using `property` decorator """ class Rectangle: def __init__(self, x1, y1, x2, y2): self.x1, self.y1 = x1, y1 self.x2, self.y2 = x2, y2 @property def width(self): """rectangle height measured from top""" return self.x2 - self.x1 @width.setter def width(self, value): self.x2 = self.x1 + value @property def height(self): """rectangle height measured from top""" return self.y2 - self.y1 @height.setter def height(self, value): self.y2 = self.y1 + value def __repr__(self): return "{}({}, {}, {}, {})".format( self.__class__.__name__, self.x1, self.y1, self.x2, self.y2 ) if __name__ == "__main__": rectangle = Rectangle(0, 0, 10, 10) print( "At start we have {} with size of {} x {}" "".format(rectangle, rectangle.width, rectangle.height) ) rectangle.width = 2 rectangle.height = 8 print( "After resizing we have {} with size of {} x {}" "".format(rectangle, rectangle.width, rectangle.height) )
false
fc8d7266535b1af6ba76aac70e15c867ee09d069
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 14 Array/array_longest_non_repeat_solution.py
2,461
4.25
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # --------------------------------------------------------------- # python best courses https://courses.tanpham.org/ # --------------------------------------------------------------- # Challenge # Given a string, find the length of the longest substring # without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", with the length of 3. # --------------------------------------------------------------- # Algorithm # In summary : Form all posible sub_strings from original string, then return length of longest sub_string # - start from 1st character, form as long as posible sub string # - Add first character to sub string # - Add second character to sub string if second character not exist in sub string # ... # - Repeate until got a character which already exist inside sub string or # - start from 2nd character, form as long as posible sub string # - Add first character to sub string # - Add second character to sub string if second character not exist in sub string # ... # - Repeate until got a character which already exist inside sub string # .... # - start from final character, form as long as posible sub string # - Add first character to sub string # - Add second character to sub string if second character not exist in sub string # ... # - Repeate until got a character which already exist inside sub string # --------------------------------------------------------------- str = "abcbb" def longest_non_repeat(str): # init start position and max length i=0 max_length = 1 for i,c in enumerate(str): # init counter and sub string value start_at = i sub_str=[] # continue increase sub string if did not repeat character while (start_at < len(str)) and (str[start_at] not in sub_str): sub_str.append(str[start_at]) start_at = start_at + 1 # update the max length if len(sub_str) > max_length: max_length = len(sub_str) print(sub_str) return max_length longest_non_repeat(str)
true
2bfd3d1c05de676850cd447ca2f9adab34335e98
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/String/SortCharactersByFrequency.py
1,384
4.15625
4
""" Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. 给定一个字符串,以字符出现的频率进行排序。 思路: 1. 用一个字典记录每个字符出现的频率。 2. 根据出现的频率排序。 3. 因为直接堆在一起即可,直接构建一个列表。 4. 在组合起来。 beat 95% 36ms. 测试地址: https://leetcode.com/problems/sort-characters-by-frequency/description/ """ c.. Solution o.. ___ frequencySort s """ :type s: str :rtype: str """ x _ # dict ___ i __ s: try: x[i] += 1 except: x[i] = 1 b = s..(x, k.._l... t: x[t], reverse=True) r_ ''.join([i*x[i] ___ i __ b])
true
f6266f2a13c31a765420db79fdb8235f06487c5e
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/_algorithms_challenges/pybites/beginner/beginner-bite-208-find-the-number-pairs-summing-up-n.py
1,075
4.34375
4
''' In this Bite you complete find_number_pairs which receives a list of numbers and returns all the pairs that sum up N (default=10). Return this list of tuples from the function. So in the most basic example if we pass in [2, 3, 5, 4, 6] it returns [(4, 6)] and if we give it [9, 1, 3, 8, 7] it returns [(9, 1), (3, 7)]. The tests check more scenarios (floats, other values of N, negative numbers). Have fun and keep calm and code in Python ''' ___ find_number_pairs(numbers, N=10 result_possible_duplicates # list ___ i __ numbers: number_to_find N - i __ number_to_find __ l..(s..(numbers) - s..([i]: result_possible_duplicates.a..((i, number_to_find result # list # Reverse tuples so we can eliminate duplicates using set ___ p __ result_possible_duplicates: a,b p temp (a,b) __ a < b ____ (b,a) result.a..(temp) r.. l..(s..(result print(find_number_pairs([0.24, 0.36, 0.04, 0.06, 0.33, 0.08, 0.20, 0.27, 0.3, 0.31, 0.76, 0.05, 0.08, 0.08, 0.67, 0.09, 0.66, 0.79, 0.95], 1
true
69ad335243346001307df683f73d09e66a0e72d3
syurskyi/Python_Topics
/095_os_and_sys/examples/realpython/018_Deleting Directories.py
1,222
4.3125
4
# The standard library offers the following functions for deleting directories: # # os.rmdir() # pathlib.Path.rmdir() # shutil.rmtree() # # To delete a single directory or folder, use os.rmdir() or pathlib.rmdir(). These two functions only work if the d # irectory you’re trying to delete is empty. If the directory isn’t empty, an OSError is raised. Here is how to delete # a folder: import os trash_dir = 'my_documents/bad_dir' try: os.rmdir(trash_dir) except OSError as e: print(f'Error: {trash_dir} : {e.strerror}') # Here, the trash_dir directory is deleted by passing its path to os.rmdir(). If the directory isn’t empty, # an error message is printed to the screen: # # Traceback (most recent call last): # File '<stdin>', line 1, in <module> # OSError: [Errno 39] Directory not empty: 'my_documents/bad_dir' # # Alternatively, you can use pathlib to delete directories: from pathlib import Path trash_dir = Path('my_documents/bad_dir') try: trash_dir.rmdir() except OSError as e: print(f'Error: {trash_dir} : {e.strerror}') # Here, you create a Path object that points to the directory to be deleted. Calling .rmdir() on the Path object # will delete it if it is empty.
true
3ea4a2eeebbb4784a57accf7184350ed53c503ff
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/SortArrayByParityII.py
968
4.21875
4
""" Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example 1: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 根据单双排列,一个双一个单。 """ c.. Solution o.. ___ sortArrayByParityII A """ :type A: List[int] :rtype: List[int] """ odd # list even # list ___ i __ A: __ i%2 __ 0: even.a.. i) ____ odd.a.. i) result # list ___ j, k __ zip(even, odd result.a.. j) result.a.. k) r_ result
true
a5ae2046a401cae347fe7a33ccf0c96ec51dcef5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/Palindrome.py
474
4.25
4
#The word or whole phrase which has the same sequence of letters in both directions is called a palindrome. ___ i __ r..(i..(i.. ))): rev_str '' s__ ''.j..(e ___ e __ i.. ).l.. __ e.islower #here iam storing the string in the reverse form ___ j __ r..(l..(s__)-1,-1,-1 rev_str += s__[j] #once the reverse string is stored then i'm comparing it with the original string __ rev_str __ s__: print('Y',' ') ____ print('N',' ')
false
c2ed4a564cc754afbee699556ef3b5483dca28ed
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/9_v2/palindrome.py
1,427
4.15625
4
# """A palindrome is a word, phrase, number, or other sequence of characters # which reads the same backward as forward""" # _______ __ # _______ u__.r.. # _______ __ # # TMP __.g.. TMP /tmp # DICTIONARY __.p...j..? dictionary_m_words.txt # u__.r...u.. # 'https://bites-data.s3.us-east-2.amazonaws.com/dictionary_m_words.txt', # ? # # # # ___ load_dictionary # """Load dictionary (sample) and return as generator (done)""" # w__ o.. ? __ f # r.. word.l...s.. ___ ? __ ?.r.. # # # ___ is_palindrome word # """Return if word is palindrome, 'madam' would be one. # Case insensitive, so Madam is valid too. # It should work for phrases too so strip all but alphanumeric chars. # So "No 'x' in 'Nixon'" should pass (see tests for more)""" # # # # word __.s.. _ \W '' w.. .l.. # # low,high 0,l.. ? - 1 # # # w.... ? < ? # __ ? l.. !_ ? h.. # r.. F.. # # l.. +_ 1 # h.. -_ 1 # # r.. T.. # # # # ___ get_longest_palindrome words_ N.. # """Given a list of words return the longest palindrome # If called without argument use the load_dictionary helper # to populate the words list""" # # __ n.. ? # words ? # # longest_length f__ "-inf" # longest N.. # ___ word __ ? # __ i.. ? # __ l.. ? > ? # l.. l. ? # l.. w.. # # r.. ? #
false
0586551822d2c81be6473a3604a06b80f558c254
syurskyi/Python_Topics
/120_design_patterns/016_iterator/examples/Iterator_003.py
1,326
4.375
4
#!/usr/bin/env python # Written by: DGC #============================================================================== class ReverseIterator(object): """ Iterates the object given to it in reverse so it shows the difference. """ def __init__(self, iterable_object): self.list = iterable_object # start at the end of the iterable_object self.index = len(iterable_object) def __iter__(self): # return an iterator return self def next(self): """ Return the list backwards so it's noticeably different.""" if (self.index == 0): # the list is over, raise a stop index exception raise StopIteration self.index = self.index - 1 return self.list[self.index] #============================================================================== class Days(object): def __init__(self): self.days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] def reverse_iter(self): return ReverseIterator(self.days) #============================================================================== if (__name__ == "__main__"): days = Days() for day in days.reverse_iter(): print(day)
true
14e23ea3e3de89813068797bce4742c01e62044d
syurskyi/Python_Topics
/045_functions/008_built_in_functions/reduce/_exercises/templates/002_Using Operator Functions.py
829
4.28125
4
# # python code to demonstrate working of reduce() # # using operator functions # # # importing functools for reduce() # ____ f.. # # # importing operator for operator functions # ____ o.. # # # initializing list # lis _ 1 3 5 6 2 # # # using reduce to compute sum of list # # using operator functions # print ("The sum of the list elements is : " e.._"" # print f____.r____ o____.a.. ? # # # using reduce to compute product # # using operator functions # print "The product of list elements is : "; e.._"" # print f___.r___ o____.m__ ? # # # using reduce to concatenate string # print "The concatenated product is : "; e.._"" # print f____.r_____ o____.a.. |"geeks" "for" "geeks" # # # Output # # # # The sum of the list elements is : 17 # # The product of list elements is : 180 # # The concatenated product is : geeksforgeeks
true
048985656c8b9aa4fdd20d5f4485302a9059ebe2
syurskyi/Python_Topics
/095_os_and_sys/examples/pathlib — Filesystem Paths as Objects/009_Deleting/001_pathlib_rmdir.py
926
4.28125
4
# There are two methods for removing things from the file system, depending on the type. To remove an empty directory, use rmdir(). # pathlib_rmdir.py # # import pathlib # # p = pathlib.Path('example_dir') # # print('Removing {}'.format(p)) # p.rmdir() # # A FileNotFoundError exception is raised if the post-conditions are already met and the directory does not exist. It is also an error to try to remove a directory that is not empty. # # $ python3 pathlib_rmdir.py # # Removing example_dir # # $ python3 pathlib_rmdir.py # # Removing example_dir # Traceback (most recent call last): # File "pathlib_rmdir.py", line 16, in <module> # p.rmdir() # File ".../lib/python3.6/pathlib.py", line 1270, in rmdir # self._accessor.rmdir(self) # File ".../lib/python3.6/pathlib.py", line 387, in wrapped # return strfunc(str(pathobj), *args) # FileNotFoundError: [Errno 2] No such file or directory: # 'example_dir'
true
331eab5b8eafeadd1f9d83d27280117a4daea3b8
syurskyi/Python_Topics
/012_lists/_exercises/Python 3 Most Nessesary/8.1. Listing 8.1. Create a shallow copy of the list.py
1,202
4.1875
4
# # -*- coding: utf-8 -*- # # x = [1, 2, 3, 4, 5] # Создали список # # Создаем копию списка # y = l.. ? # или с помощью среза: y = x[:] # # или вызовом метода copy(): y = x.copy() # print ? # # [1, 2, 3, 4, 5] # print(x i_ y) # Оператор показывает, что это разные объекты # # False # y[1] = 100 # Изменяем второй элемент # print(x, y) # Изменился только список в перемеой y # # ([1, 2, 3, 4, 5], [1, 100, 3, 4, 5]) # # # x = [1, [2, 3, 4, 5]] # Создали вложенный список # y = l.. ? # Якобы сделали копию списка # print(x i_ y) # Разные объекты # # False # y 1 1 = 100 # Изменяем элемент # print(x, y) # Изменение затронуло переменную x!!! # # ([1, [2, 100, 4, 5]], [1, [2, 100, 4, 5]])
false
7f571f75e4cde471f37e78d7b6e3f64255c5e9dd
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/topics/String/8/test_rotate.py
1,794
4.46875
4
____ rotate _______ rotate ___ test_small_rotate ... rotate('hello', 2) __ 'llohe' ... rotate('hello', -2) __ 'lohel' ___ test_bigger_rotation_of_positive_n s__ 'bob and julian love pybites!' e.. 'love pybites!bob and julian ' ... rotate(s__, 15) __ e.. ___ test_bigger_rotation_of_negative_n s__ 'pybites loves julian and bob!' e.. 'julian and bob!pybites loves ' ... rotate(s__, -15) __ e.. ___ test_rotation_of_n_same_as_len_str s__ e.. 'julian and bob!' ... rotate(s__, l..(s__ __ e.. ___ test_rotation_of_n_bigger_than_string """ Why are there two expected results for this test? This Bite can be interpreted in two ways: 1. A slice of size n moved from one end of the string to the other 2. A continual rotation, character by character, n number of times Both interpretations result in identical output, except in the case where the rotation size exceeds the length of the string. Case 1) With a slice method, slicing an entire string and placing it at either the beginning or end of itself simply results in the the original string = expected_solution1 Case 2) With a continual rotation, rotating the string len(string) number of times produces a string idential to the original string. This means any additional rotations can be considered equivalent to rotating the string by rotations % len(string) = expected_solution2 """ s__ 'julian and bob!' expected_solution1 'julian and bob!' expected_solution2 ' bob!julian and' ... rotate(s__, 100) __ (expected_solution1, expected_solution2) mod 100 % l..(s__) # 10 ... rotate(s__, mod) __ (expected_solution1, expected_solution2)
false
ce65f63521103a3b65819c8bdf7daaaf479a51ef
syurskyi/Python_Topics
/012_lists/_exercises/ITVDN Python Starter 2016/03-slicing.py
822
4.4375
4
# -*- coding: utf-8 -*- # Можно получить группу элементов по их индексам. # Эта операция называется срезом списка (list slicing). # Создание списка чисел my_list = [5, 7, 9, 1, 1, 2] # Получение среза списка от нулевого (первого) элемента (включая его) # до третьего (четвёртого) (не включая) sub_list = my_list[0:3] # Вывод полученного списка print(sub_list) # Вывод элементов списка от второго до предпоследнего print(my_list[2:-2]) # Вывод элементов списка от четвёртого (пятого) до пятого (шестого) print(my_list[4:5])
false
a64c2c4481a7f03ccad171656f3430c81f4496db
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-18-find-the-most-common-word.py
2,185
4.25
4
""" Write a function that returns the most common (non stop)word in this Harry Potter text. Make sure you convert to lowercase, strip out non-alphanumeric characters and stopwords. Your function should return a tuple of (most_common_word, frequency). The template code already loads the Harry Potter text and list of stopwords in. Check the tests for more info - have fun! KEYWORDS: Counter, data analysis, list comprehensions """ _______ __ _______ u__.r.. _______ s__ ____ c.. _______ C.. _______ __ # data provided tmp __.g.. TMP /tmp stopwords_file __.p...j.. ? 'stopwords') harry_text __.p...j.. ? 'harry') u__.r...u..( 'https://bites-data.s3.us-east-2.amazonaws.com/stopwords.txt', stopwords_file ) u__.r...u..( 'https://bites-data.s3.us-east-2.amazonaws.com/harry.txt', harry_text ) ___ my_solution_get_harry_most_common_word """ High level concept: * prepare a list with stopwords * go over text word by word, stripping all non-alphanumeric characters * if a word does not exist in stopwords list, add it to another list (let's call it filtered) * once we have filtered list ready, feed it to the counter object * retrieve 1st most common object and return it """ stopwords # list filtered # list f1 o.. stopwords_file, _ ___ line __ f1: stopwords.a..(line.s.. f2 o.. harry_text, _ ___ line __ f2: ___ word __ line.s.. : print(word) p word.s..(s__.p...l.. __ l..(p) > 0 a.. p n.. __ stopwords: filtered.a..(word.s..(s__.p...l.. counter C..(filtered) r.. counter.most_common(1 0 ___ pyb_solution_get_harry_most_common_word ___ get_harry_most_common_word w__ o.. stopwords_file) __ f: stopwords s..(f.r...s...l...s..('\n' w__ o.. harry_text) __ f: words [__.s.. _ \W+', r'', word) # [^a-zA-Z0-9_] ___ word __ f.r...l...s.. ] words [word ___ word __ words __ word.s.. a.. word n.. __ stopwords] cnt C..(words) r.. cnt.most_common(1 0 print(my_solution_get_harry_most_common_word
true
d6457e1f59aa2e7f58e030cdc15209bc2e73432b
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 3 Search Algorithms/LinearSearch.py
489
4.1875
4
___ linear_search(container, item # the running time of this algorithms is O(N) # USE LINEAR SEARCH IF THE DATA STRUCTURE IS UNORDERED !!! ___ index __ ra__(le_(container)): __ container[index] __ item: # if we find the item: we return the index of that item r_ index # search miss - when the item is not present in the # underlying data structure (container) r_ -1 nums [1, 5, -3, 10, 55, 100] print(linear_search(nums, 10))
true
ab0688242ee45e648ef23c6aea22c389a47fb746
syurskyi/Python_Topics
/095_os_and_sys/_exercises/exercises/realpython/017_Deleting Files in Python.py
2,381
4.28125
4
# # To delete a single file, use pathlib.Path.unlink(), os.remove(). or os.unlink(). # # os.remove() and os.unlink() are semantically identical. To delete a file using os.remove(), do the following: # # ______ __ # # data_file _ 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt' # __.r.. ? # # # Deleting a file using os.unlink() is similar to how you do it using os.remove(): # # ______ __ # # data_file _ 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt' # __.u.. ? # # # Calling .unlink() or .remove() on a file deletes the file from the filesystem. These two functions will throw # # an OSError if the path passed to them points to a directory instead of a file. To avoid this, you can either check # # that what you’re trying to delete is actually a file and only delete it if it is, or you can use exception handling # # to handle the OSError: # # ______ __ # # data_file _ 'home/data.txt' # # # If the file exists, delete it # __ __.p...i_f_ ? # __.r.. ? # ____ # print _*Error: |? not a valid filename') # # # os.path.isfile() checks whether data_file is actually a file. If it is, it is deleted by the call to os.remove(). # # If data_file points to a folder, an error message is printed to the console. # # The following example shows how to use exception handling to handle errors when deleting files: # # ______ __ # # data_file _ 'home/data.txt' # # # Use exception handling # ___ # __.r.. ? # ______ O.. __ e # print _*Error: |? : |?.s_e.. # # # The code above attempts to delete the file first before checking its type. If data_file isn’t actually a file, # # the OSError that is thrown is handled in the ______ clause, and an error message is printed to the console. # # The error message that gets printed out is formatted using Python f-strings. # # # # Finally, you can also use pathlib.Path.unlink() to delete files: # # ____ p_l_ ______ P.. # # data_file _ P..('home/data.txt') # # ___ # ?.u.. # ______ Is.. __ e # print _*Error: |? : |?.s_e.. # # # This creates a Path object called data_file that points to a file. Calling .remove() on data_file will # # delete home/data.txt. If data_file points to a directory, an IsADirectoryError is raised. It is worth noting that # # the Python program above has the same permissions as the user running it. If the user does not have permission # # to delete the file, a PermissionError is raised.
true
b6e934cfc5af74841bd8c4a8f951220163ce6bb0
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 92 - SortColours.py
757
4.15625
4
# Sort Colours # Question: Given an array with n objects coloured red, white or blue, sort them so that objects of the same colour are adjacent, with the colours in the order red, white and blue. # Here, we will use the integers 0, 1, and 2 to represent the colour red, white, and blue respectively. # Note: You are not supposed to use the library's sort function for this problem # Solutions: class Solution: # @param A a list of integers # @return sorted A, sort in place def sortColors(self, A): color=[0]*3 for i in A: color[i] += 1 i = 0 for x in range(3): for j in range(color[x]): A[i]=x i+=1 return A Solution().sortColors([1,2,0,1,2,0])
true
8b3ff422b9e6313a0af0302c628c4179f750d85e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/227 Basic Calculator II py3.py
2,303
4.21875
4
#!/usr/bin/python3 """ Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Output: 7 Example 2: Input: " 3/2 " Output: 1 Example 3: Input: " 3+5 / 2 " Output: 5 Note: You may assume that the given expression is always valid. Do not use the eval built-in library function. """ c_ Solution: ___ calculate s: s..) __ i.. """ No brackets. Look at previous operand and operator, when finishing scanning current operand. """ operand 0 stk # list prev_op "+" ___ i, c __ e..(s __ c.i.. operand operand * 10 + i..(c) # i == len(s) - 1 delimited c __ ("+", "-", "*", "/") o. i __ l..(s) - 1 __ delimited: __ prev_op __ "+": cur operand ____ prev_op __ "-": cur -operand ____ prev_op __ "*": cur stk.p.. ) * operand ____ ... prev_op __ "/" # instead of op1 // op2 due to negative handling, -3 // 2 == -2 cur i..(stk.p.. ) / operand) stk.a..(cur) prev_op c operand 0 r.. s..(stk) ___ calculate_error s: s..) __ i.. """ cannot use dictionary, since it is eager evaluation """ operand 0 stk # list prev_op "+" ___ i, c __ e..(s __ c.i.. operand operand * 10 + i..(c) # i == len(s) - 1 delimited c __ ("+", "-", "*", "/") o. i __ l..(s) - 1 __ delimited: cur { "+": operand, "-": -operand, "*": stk.p.. ) * operand, "/": i..(stk.p.. ) / operand), # instead of op1 // op2 due to negative handling, -3 // 2 == -2 }[prev_op] stk.a..(cur) prev_op c operand 0 r.. s..(stk) __ _______ __ _______ ... Solution().calculate("3+2*2") __ 7
true
58cf2e0e3efb0f44bce7b4ef7c203fc27a443842
syurskyi/Python_Topics
/095_os_and_sys/examples/realpython/005_Listing All Files in a Directory.py
2,565
4.375
4
# This section will show you how to print out the names of files in a directory using os.listdir(), os.scandir(), # and pathlib.Path(). To filter out directories and only list files from a directory listing produced by os.listdir(), # use os.path: # import os # List all files in a directory using os.listdir basepath = 'my_directory/' for entry in os.listdir(basepath): if os.path.isfile(os.path.join(basepath, entry)): print(entry) print() print() # # Here, the call to os.listdir() returns a list of everything in the specified path, and then that list is filtered # by os.path.isfile() to only print out files and not directories. This produces the following output: # # file1.py # file3.txt # file2.csv # # An easier way to list files in a directory is to use os.scandir() or pathlib.Path(): # import os # List all files in a directory using scandir() basepath = 'my_directory/' with os.scandir(basepath) as entries: for entry in entries: if entry.is_file(): print(entry.name) print() print() # Using os.scandir() has the advantage of looking cleaner and being easier to understand than using os.listdir(), # even though it is one line of code longer. Calling entry.is_file() on each item in the ScandirIterator returns # True if the object is a file. Printing out the names of all files in the directory gives you the following output: # # file1.py # file3.txt # file2.csv # # Here’s how to list files in a directory using pathlib.Path(): from pathlib import Path basepath = Path('my_directory/') files_in_basepath = basepath.iterdir() for item in files_in_basepath: if item.is_file(): print(item.name) print() print() # Here, you call .is_file() on each entry yielded by .iterdir(). The output produced is the same: # # file1.py # file3.txt # file2.csv # # The code above can be made more concise if you combine the for loop and the if statement into # a single generator expression. Dan Bader has an excellent article on generator expressions and list comprehensions. # # The modified version looks like this: from pathlib import Path # List all files in directory using pathlib basepath = Path('my_directory/') files_in_basepath = (entry for entry in basepath.iterdir() if entry.is_file()) for item in files_in_basepath: print(item.name) # This produces exactly the same output as the example before it. This section showed that filtering files # or directories using os.scandir() and pathlib.Path() feels more intuitive and looks cleaner than using os.listdir() # in conjunction with os.path.
true
29313678d25756a660eef4638259ee18459be08c
syurskyi/Python_Topics
/125_algorithms/_examples/Practice_Python_by_Solving_100_Python_Problems/77.py
219
4.125
4
#Create a script that gets user's age and returns year of birth from datetime import datetime age = int(input("What's your age? ")) year_birth = datetime.now().year - age print("You were born back in %s" % year_birth)
true
08eff574578ac91abce96916bc188833ac922619
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-3-word-values.py
2,365
4.3125
4
""" Calculate the dictionary word that would have the most value in Scrabble. There are 3 tasks to complete for this Bite: First write a function to read in the dictionary.txt file (= DICTIONARY constant), returning a list of words (note that the words are separated by new lines). Second write a function that receives a word and calculates its value. Use the scores stored in LETTER_SCORES. Letters that are not in LETTER_SCORES should be omitted (= get a 0 score). With these two pieces in place, write a third function that takes a list of words and returns the word with the highest value. Look at the TESTS tab to see what your code needs to pass. Enjoy! """ import os import u__.r.. # PREWORK TMP = os.getenv("TMP", "/tmp") print(TMP) S3 = 'https://bites-data.s3.us-east-2.amazonaws.com/' DICT = 'dictionary.txt' DICTIONARY = os.path.join(TMP, DICT) print(DICTIONARY) u__.r...u..(f'{S3}{DICT}', DICTIONARY) scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"), (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")] LETTER_SCORES = {letter: score for score, letters in scrabble_scores for letter in letters.split()} # start coding def load_words_v1(): """Load the words dictionary (DICTIONARY constant) into a list and return it""" l = [] with open(DICTIONARY) as file: for line in file: l.append(line.strip()) return l def load_words_v2(): with open(DICTIONARY) as file: return [word.strip() for word in file.read().split()] def calc_word_value_v1(word): """Given a word calculate its value using the LETTER_SCORES dict""" value = 0 for char in word.upper(): try: value += LETTER_SCORES[char] except: value = 0 return value def calc_word_value_v2(word): return sum(LETTER_SCORES.get(char.upper(), 0) for char in word) def max_word_value(words): """Given a list of words calculate the word with the maximum value and return it""" max = () for word in words: value = calc_word_value(word) if max == (): max = (word, value) else: if value > max[1]: max = (word, value) return max[0] def max_word_value_v2(words): return max(words, key=calc_word_value) print(max_word_value(['zime', 'fgrtgtrtvv']))
true
dccee39c84fc8a8b20b0cb56c22b64111a294a7d
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/intro/intro-bite102-infinite-loop-input-continue-break.py
1,151
4.15625
4
VALID_COLORS = ['blue', 'yellow', 'red'] def my_print_colors(): """Ask for color, lowercase it, check if 'quit' is entered, if so print 'bye' and break, next check if given color is in VALID_COLORS, if not, continue, finally if that check passes, print the color""" while True: inp = input("Enter color:").lower() if inp == 'quit': print("bye") break if inp not in VALID_COLORS: print("Not a valid color") continue # this else is useless else: print(inp) # thou shall not stop after a match!!! break def print_colors(): """Ask for color, lowercase it, check if 'quit' is entered, if so print 'bye' and break, next check if given color is in VALID_COLORS, if not, continue, finally if that check passes, print the color""" while True: color = input('Enter a color: ').lower() if color == 'quit': print('bye') break if color not in VALID_COLORS: print('Not a valid color') continue print(color) print_colors()
true
b7bad63ce92b0c02cb75adfbd722b04af3be1127
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 93 - SpiralMatrix.py
1,543
4.15625
4
# Spiral Matrix # Question: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. # For example: # Given the following matrix: # [ [ 1, 2, 3 ], # [ 4, 5, 6 ], # [ 7, 8, 9 ] ] # You should return [1,2,3,6,9,8,7,4,5]. # Solutions: class Solution: # @param matrix, a list of lists of integers # @return a list of integers def spiralOrder(self, matrix): if matrix == []: return [] res = [] maxUp = maxLeft = 0 maxDown = len(matrix) - 1 maxRight = len(matrix[0]) - 1 direct = 0 # 0 go right, 1 go down, 2 go left, 3 go up while True: if direct == 0: # go right for i in range(maxLeft, maxRight + 1): res.append(matrix[maxUp][i]) maxUp += 1 elif direct == 1: # go down for i in range(maxUp, maxDown + 1): res.append(matrix[i][maxRight]) maxRight -= 1 elif direct == 2: # go left for i in reversed(range(maxLeft, maxRight + 1)): res.append(matrix[maxDown][i]) maxDown -= 1 else: # go up for i in reversed(range(maxUp, maxDown + 1)): res.append(matrix[i][maxLeft]) maxLeft += 1 if maxUp > maxDown or maxLeft > maxRight: return res direct = (direct + 1) % 4 Solution().spiralOrder([ [ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ] ])
true
1dde8cb11156223aecd6a4a81853f4045270155d
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/299_v4/base_converter.py
780
4.34375
4
def digit_map(num): """maps numbers greater than a single digit to letters (UPPER)""" return chr(num + 55) if num > 9 else str(num) def convert(number: int, base: int = 2) -> str: """Converts an integer into any base between 2 and 36 inclusive Args: number (int): Integer to convert base (int, optional): The base to convert the integer to. Defaults to 2. Raises: Exception (ValueError): If base is less than 2 or greater than 36 Returns: str: The returned value as a string """ if base < 2 or base > 36: raise ValueError digits = [] while number > 0: digits.append(number % base) number //= base digits = list(map(digit_map, digits)) return ''.join(reversed(digits))
true
2320ff2a2f62a49a58ed296a3886563432f3132f
syurskyi/Python_Topics
/070_oop/004_inheritance/_exercises/templates/super/Python Super/002_ Single Inheritance.py
2,396
4.28125
4
# # Inheritance is the concept in object-oriented programming in which a class derives (or inherits) attributes # # and behaviors from another class without needing to implement them again. # # # See the following program. # # # app.py # # c_ Rectangle # __ - length width # ? ? # ? ? # # __ area # r_ ? * ? # # __ perimeter # r_ 2 * l.. + 2 * w.. # # # c_ Square # __ - length # ? ? # # __ area # r_ l.. * l.. # # __ perimeter # r_ 4 * l.. # # # sqr _ S.. 4 # print("Area of Square is:", ?.a.. # # rect _ R.. 2 4 # # # See the output. # # # # pyt python3 app.py # # Area of Square is: 16 # # Area of Rectangle is: 8 # # pyt # # # In the above example, you have two shapes that are related to each other: The square is, which is the particular # # kind of rectangle. # # # # The code, however, doesn't reflect the relationship between those two shapes and thus has code that is necessarily # # repeated. We need to apply basic code principles like Do not repeat yourself. # # # # By using the proper way of inheritance, you can reduce the amount of code you write while simultaneously # # reflecting the real-world relationship between those shapes like rectangles and squares. # # # app.py # # c_ Rectangle # __ - lengt width # ? ? # ? ? # # __ area # r_ ? * ? # # __ perimeter # r_ 2 * ? + 2 * ? # # c_ Square R.. # __ - length # s__. - l.. l.. # # # sqr _ S.. 4 # print("Area of Square is:" ?.a.. # # rect _ R. 2 4 # print("Area of Rectangle is:" ?.a.. # # # In this example, a Rectangle is a superclass, and Square is a subclass because the Square and Rectangle __init__() # # methods are so related, we can call a superclass's __init__() method (Rectangle.__init__()) from that of Square # # by using a super() keyword. # # # # This sets the length and width attributes even though you just had to supply the single length parameter to a Square constructor. # # # # When you run this, even though your Square class doesn't explicitly implement it, the call to .area() will use # # an area() method in the superclass and print 16. # # # # The Square class inherited .area() from the Rectangle class. # # # # See the output. # # # # pyt python3 app.py # # Area of Square is: 16 # # Area of Rectangle is: 8 # # pyt # # It is the same as above. #
false
961312152de7cdc52600dbbce3f98d379605f5a4
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/159/calculator.py
724
4.125
4
# _______ o.. # # ___ simple_calculator calculation # """Receives 'calculation' and returns the calculated result, # # Examples - input -> output: # '2 * 3' -> 6 # '2 + 6' -> 8 # # Support +, -, * and /, use "true" division (so 2/3 is .66 # rather than 0) # # Make sure you convert both numbers to ints. # If bad data is passed in, raise a ValueError. # """ # ___ # num1 op num2 ?.s.. " " # num1, num2 i.. ? i.. ? # ______ V.. # r.. V... # # ops # "+": o__.a.. # "-": o__.s.. # "*": o__.m.. # "/": o__.t.. # # # ___ # r.. ? o. ? ? # ______ K.. Z.. # r.. V... # # # __ _______ __ _______ # print ? "2 * 3"
false
dc8846f3e74b784dcee36049f2735d7dd2ae3c4d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/581 Shortest Unsorted Continuous Subarray.py
2,052
4.3125
4
#!/usr/bin/python3 """ Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means <=. """ ____ t___ _______ L.. c_ Solution: ___ findUnsortedSubarray nums: L.. i.. __ i.. """ Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value nums[lo - 1] <= min && max <= nums[hi + 1] """ n l..(nums) lo, hi 0, n - 1 w.... lo < hi a.. nums[lo] <_ nums[lo + 1]: lo += 1 w.... lo < hi a.. nums[hi - 1] <_ nums[hi]: hi -_ 1 __ hi <_ lo: r.. 0 mini f__('inf') maxa -f__('inf') ___ i __ r..(lo, hi + 1 mini m..(mini, nums[i]) maxa m..(maxa, nums[i]) w.... lo - 1 >_ 0 a.. nums[lo - 1] > mini: lo -_ 1 w.... hi + 1 < n a.. nums[hi + 1] < maxa: hi += 1 r.. hi - lo + 1 ___ findUnsortedSubarray_sort nums: L.. i.. __ i.. """ Brute force sort and compare O(n lgn) """ e.. l..(s..(nums i 0 w.... i < l..(nums) a.. nums[i] __ e..[i]: i += 1 j l..(nums) - 1 w.... j >_ i a.. nums[j] __ e..[j]: j -_ 1 r.. j - i + 1 __ _______ __ _______ ... Solution().findUnsortedSubarray([2, 1]) __ 2 ... Solution().findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15]) __ 5
true
7a183c9f407ec53a128bb57bfd6e5f0f9e10df7d
syurskyi/Python_Topics
/070_oop/008_metaprogramming/_exercises/templates/Abstract Classes in Python/a_004_Concrete Methods in Abstract Base Classes.py
848
4.21875
4
# # Concrete Methods in Abstract Base Classes : # # Concrete classes contain only concrete (normal)methods whereas abstract class contains both concrete methods # # as well as abstract methods. Concrete class provide an implementation of abstract methods, the abstract base class # # can also provide an implementation by invoking the methods via super(). # # Let look over the example to invoke the method using super(): # # # Python program invoking a # # method using super() # # _____ a.. # ____ a.. _____ A.. a.. # # # c_ R A... # ___ rk # print("Abstract Base Class") # # # c_ K R # ___ rk # s__ .? # print("subclass ") # # # Driver code # # # r = K() # r.rk() # # # Output: # # # # Abstract Base Class # # subclass # # In the above program, we can invoke the methods in abstract classes by using super().
true
98357c37192a91a3dc3afbe121908ae36db45019
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 84 - ReverseInt.py
382
4.15625
4
# Reverse Integer # Question: Reverse digits of an integer. # Example1: x = 123, return 321 # Example2: x = -123, return -321. # Solutions: class Solution: # @return an integer def reverse(self, x): if x<0: sign = -1 else: sign = 1 strx=str(abs(x)) r = strx[::-1] return sign*int(r) Solution().reverse(123)
true
c9481862292b011e70bf73b3d62078e3a0122ab7
syurskyi/Python_Topics
/120_design_patterns/025_without_topic/examples/MonoState.py
2,609
4.28125
4
#!/usr/bin/env python # Written by: DGC # python imports #============================================================================== class MonoState(object): __data = 5 @property def data(self): return self.__class__.__data @data.setter def data(self, value): self.__class__.__data = value #============================================================================== class MonoState2(object): pass def add_monostate_property(cls, name, initial_value): """ Adds a property "name" to the class "cls" (should pass in a class object not a class instance) with the value "initial_value". This property is a monostate property so all instances of the class will have the same value property. You can think of it being a singleton property, the class instances will be different but the property will always be the same. This will add a variable __"name" to the class which is the internal storage for the property. Example usage: class MonoState(object): pass add_monostate_property(MonoState, "data", 5) m = MonoState() # returns 5 m.data """ internal_name = "__" + name def getter(self): return getattr(self.__class__, internal_name) def setter(self, value): setattr(self.__class__, internal_name, value) def deleter(self): delattr(self.__class__, internal_name) prop = property(getter, setter, deleter, "monostate variable: " + name) # set the internal attribute setattr(cls, internal_name, initial_value) # set the accesser property setattr(cls, name, prop) #============================================================================== if (__name__ == "__main__"): print("Using a class:") class_1 = MonoState() print("First data: " + str(class_1.data)) class_1.data = 4 class_2 = MonoState() print("Second data: " + str(class_2.data)) print("First instance: " + str(class_1)) print("Second instance: " + str(class_2)) print("These are not singletons, so these are different instances") print("") print("") print("Dynamically adding the property:") add_monostate_property(MonoState2, "data", 5) dynamic_1 = MonoState2() print("First data: " + str(dynamic_1.data)) dynamic_1.data = 4 dynamic_2 = MonoState2() print("Second data: " + str(dynamic_2.data)) print("First instance: " + str(dynamic_1)) print("Second instance: " + str(dynamic_2)) print("These are not singletons, so these are different instances")
true
dcd947e7c695994dce361540224d3b63d3bb4d7a
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/336 Palindrome Pairs.py
2,980
4.125
4
#!/usr/bin/python3 """ Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Example 1: Input: ["abcd","dcba","lls","s","sssll"] Output: [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"] Example 2: Input: ["bat","tab","cat"] Output: [[0,1],[1,0]] Explanation: The palindromes are ["battab","tabbat"] """ ____ t___ _______ L.. ____ c.. _______ d.. c_ TrieNode: ___ - pali_prefix_idxes # list # suffix ends, prefix pali word_idx N.. children d..(TrieNode) c_ Solution: ___ palindromePairs words: L..s.. __ L..[L..[i..]]: """ Brute force, i, j and then check palindrom O(N^2 * L) Reverse the str, and then check O(N * L). Does it work actually? Check: map str -> idx |---s1---|---s2--| |---s1---|-s2-| |-s1-|---s2---| Need to check whether part of the str is palindrome. Part of str -> Trie. How to check part of the str. Useful Better way of checking palindrome? Infamouse Manacher word_i | word_j abc pppp | cba abc | pppp cba If palindrome suffix in work_i, we only need to check the "abc" against word_j Similarly for palindrome prefix in word_j Construct Trie for word_j reversely, since word_j is being checked """ root TrieNode() ___ idx, w __ e..(words cur root ___ i __ r..(l..(w) - 1, -1, -1 # cur.children[w[i]] # error, pre-advancing the trie is unable to handle empty str __ is_palindrome(w, 0, i + 1 cur.pali_prefix_idxes.a..(idx) cur cur.children[w[i]] cur.pali_prefix_idxes.a..(idx) # empty str is palindrome cur.word_idx idx # word ends ret # list ___ idx, w __ e..(words cur root ___ i __ r..(l..(w: # cur.children.get(w[i], None) # error, pre-advancing the trie is unable to handle empty str __ is_palindrome(w, i, l..(w a.. cur.word_idx __ n.. N.. a.. cur.word_idx !_ idx: ret.a..([idx, cur.word_idx]) cur cur.children.g.. w[i], N..) __ cur __ N.. _____ ____ ___ idx_j __ cur.pali_prefix_idxes: __ idx !_ idx_j: ret.a..([idx, idx_j]) r.. ret ___ is_palindrome w, lo, hi i lo j hi - 1 w.... i < j: __ w[i] !_ w[j]: r.. F.. i += 1 j -_ 1 r.. T.. __ _______ __ _______ ... Solution().palindromePairs(["a", ""]) __ [[0,1],[1,0]] ... Solution().palindromePairs(["abcd","dcba","lls","s","sssll"]) __ [[0,1],[1,0],[2,4],[3,2]]
false
42ea23542608d894bf2c4c50394464b9d68d0eeb
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/769 Max Chunks To Make Sorted.py
1,315
4.28125
4
#!/usr/bin/python3 """ Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array. What is the most number of chunks we could have made? Example 1: Input: arr = [4,3,2,1,0] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted. Example 2: Input: arr = [1,0,2,3,4] Output: 4 Explanation: We can split into two chunks, such as [1, 0], [2, 3, 4]. However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible. Note: arr will have length in range [1, 10]. arr[i] will be a permutation of [0, 1, ..., arr.length - 1]. """ ____ t___ _______ L.. c_ Solution: ___ maxChunksToSorted arr: L.. i.. __ i.. """ compared to the sorted [0, 1, 2, 3, 4] [1, 0, 2, 3, 4] The largest number in the chunk determines the ending index of the chunk """ ret 0 cur_max_idx 0 ___ i __ r..(l..(arr: cur_max_idx m..(cur_max_idx, arr[i]) __ i __ cur_max_idx: ret += 1 r.. ret
true
0291f8953312c8c71a778cb5defd91ca5c24ef09
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/AdvancedPython_OOP_with_Real_Words_Programs/App-6-Project-Calorie-Webapp/src/calorie.py
564
4.125
4
____ temperature _____ Temperature c_ Calorie: """Represents optimal calorie amount a person needs to take today""" ___ - weight, height, age, temperature): weight weight height height age age temperature temperature ___ calculate _ result 10 * weight + 6.5 * height + 5 - temperature * 10 r_ result __ _______ __ _______ temperature Temperature(country"italy", city"rome").get() calorie Calorie(weight70, height175, age32, temperaturetemperature) print(calorie.calculate())
true
23c0c2ee5b6165c16168522bf61bc190696b3161
syurskyi/Python_Topics
/079_high_performance/examples/Writing High Performance Python/item_49.py
1,819
4.15625
4
import logging from pprint import pprint from sys import stdout as STDOUT # Example 1 def palindrome(word): """Return True if the given word is a palindrome.""" return word == word[::-1] assert palindrome('tacocat') assert not palindrome('banana') # Example 2 print(repr(palindrome.__doc__)) # Example 3 """Library for testing words for various linguistic patterns. Testing how words relate to each other can be tricky sometimes! This module provides easy ways to determine when words you've found have special properties. Available functions: - palindrome: Determine if a word is a palindrome. - check_anagram: Determine if two words are anagrams. ... """ # Example 4 class Player(object): """Represents a player of the game. Subclasses may override the 'tick' method to provide custom animations for the player's movement depending on their power level, etc. Public attributes: - power: Unused power-ups (float between 0 and 1). - coins: Coins found during the level (integer). """ # Example 5 import itertools def find_anagrams(word, dictionary): """Find all anagrams for a word. This function only runs as fast as the test for membership in the 'dictionary' container. It will be slow if the dictionary is a list and fast if it's a set. Args: word: String of the target word. dictionary: Container with all strings that are known to be actual words. Returns: List of anagrams that were found. Empty if none were found. """ permutations = itertools.permutations(word, len(word)) possible = (''.join(x) for x in permutations) found = {word for word in possible if word in dictionary} return list(found) assert find_anagrams('pancakes', ['scanpeak']) == ['scanpeak']
true
2f0cd45309945619d5e95e75abf7be9718989ddf
syurskyi/Python_Topics
/120_design_patterns/009_decorator/_exercises/templates/decorator_003.py
1,334
4.1875
4
# """Decorator pattern # # Decorator is a structural design pattern. It is used to extend (decorate) the # functionality of a certain object at run-time, independently of other instances # of the same class. # The decorator pattern is an alternative to subclassing. Subclassing adds # behavior at compile time, and the change affects all instances of the original # class; decorating can provide new behavior at run-time for selective objects. # """ # # # c_ Component o.. # # # method we want to decorate # # ___ whoami # print("I am @".f.. i. ? # # # method we don't want to decorate # # ___ another_method # print("I am just another method of @".f.. -c. -n # # # c_ ComponentDecorator o.. # # ___ - decoratee # _? ? # reference of the original object # # ___ whoami # print("start of decorated method") # _d___.w.. # print("end of decorated method") # # # forward all "Component" methods we don't want to decorate to the # # "Component" pointer # # ___ -g name # r_ g.. _d... ? # # # ___ main # a = C... # original object # b = CD__ ? # decorate the original object at run-time # print("Original object") # a.w... # a.a.. # print("\nDecorated object") # b.w.. # b.a.. # # # __ _______ __ ______ # ?
true
1e11e649770bc1016e7babd381ba315750367a03
syurskyi/Python_Topics
/045_functions/008_built_in_functions/map/examples/006_Python map() with string.py
2,072
4.375
4
def to_upper_case(s): return str(s).upper() def print_iterator(it): for x in it: print(x, end=' ') print('') # for new line # map() with string map_iterator = map(to_upper_case, 'abc') print(type(map_iterator)) print_iterator(map_iterator) # Output: # <class 'map'> # A B C # Python map() with tuple # map() with tuple map_iterator = map(to_upper_case, (1, 'a', 'abc')) print_iterator(map_iterator) # Output: # 1 A ABC # Python map() with list map_iterator = map(to_upper_case, ['x', 'a', 'abc']) print_iterator(map_iterator) # X A ABC # Converting map to list, tuple, set map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_list = list(map_iterator) print(my_list) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_set = set(map_iterator) print(my_set) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_tuple = tuple(map_iterator) print(my_tuple) # Output: # ['A', 'B', 'C'] # {'C', 'B', 'A'} # ('A', 'B', 'C') # Python map() with lambda list_numbers = [1, 2, 3, 4] map_iterator = map(lambda x: x * 2, list_numbers) print_iterator(map_iterator) # Output: # 2 4 6 8 # map() with multiple iterable arguments list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8) map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers) print_iterator(map_iterator) # Output: 5 12 21 32 # map() with multiple iterable arguments of different sizes list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8, 9, 10) map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers) print_iterator(map_iterator) map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers) print_iterator(map_iterator) # Output: # 5 12 21 32 # 5 12 21 32 # Python map() with function None # map_iterator = map(None, 'abc') # print(map_iterator) # for x in map_iterator: # print(x) # Output: # # # Traceback (most recent call last): # File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in <module> # for x in map_iterator: # TypeError: 'NoneType' object is not callable
false
ee5aada9b9038f1262e4b8d07a2ad5bdeb8a076c
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/advanced/42/guess.py
2,517
4.15625
4
# _______ r__ # MAX_GUESSES 5 # START, END 1, 20 # # # ___ get_random_number # """Get a random number between START and END, returns int""" # r.. r__.r.. ? # # # c_ Game # """Number guess class, make it callable to initiate game""" # # ___ - # """Init _guesses, _answer, _win to set(), get_random_number(), False""" # _guesses s.. # _answer ? # _win F.. # # # # # # ___ guess # """Ask user for input, convert to int, raise ValueError outputting # the following errors when applicable: # 'Please enter a number' # 'Should be a number' # 'Number not in range' # 'Already guessed' # If all good, return the int""" # # w... T... # ___ # number i.. "Guess a number between 1 and 20: ") # result i.. ? # ______: # __ ? __ N.. o. l.. ? __ 0 # print('Please enter a number') # ____ # print('Should be a number') # r.. V... # ____ # __ n.. ? <_ ? <_ ? # print('Number not in range') # ____ ? __ _? # print('Already guessed') # ____ # _?.a.. ? # r.. ? # r.. V... # # # # # # # # # # ___ _validate_guess guess # """Verify if guess is correct, print the following when applicable: # {guess} is correct! # {guess} is too low # {guess} is too high # Return a boolean""" # # correct F.. # __ ? __ _answer # print _*? is correct! # ? T.. # ____ ? > _? # print _*? is too high # ____ # print _*? is too low # # r.. ? # ___ -c # """Entry point / game loop, use a loop break/continue, # see the tests for the exact win/lose messaging""" # # # ___ i __ r.. 1 M.. + 1 # w... T... # ___ # user_guess ? # ______ V.. # p.. # ____ # _____ # # # _win _v.. u.. # # # __ ? # _____ # # # __ ? # print _*It took you ? guesses # ____ # print _*Guessed 5 times, answer was ? # # # # # # # # # # # # __ _____ __ _____ # game ? # g?
false
1be54b84d0949dc683432acfc41b13cde9f570c1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+99 How to calculate the Area and Perimeter of Right Angle Triangle.py
276
4.1875
4
_______ math x float(input("Insert length of x: ")) y float(input("Insert length of y: ")) z math.sqrt((pow(x,2)+pow(y,2))) Area (x*y)/2 Perimeter x+y+z print("Area of right angled triangle = %.2f" % Area) print("Perimeter of right angled triangle = %.2f" % Perimeter)
false
b7e17d3710c68df3ebf3b937d389f40cf4257d7e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/959 Regions Cut By Slashes.py
2,876
4.1875
4
#!/usr/bin/python3 """ In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space. These characters divide the square into contiguous regions. (Note that backslash characters are escaped, so a \ is represented as "\\".) Return the number of regions. Example 1: Input: [ " /", "/ " ] Output: 2 Explanation: The 2x2 grid is as follows: Example 2: Input: [ " /", " " ] Output: 1 Explanation: The 2x2 grid is as follows: Example 3: Input: [ "\\/", "/\\" ] Output: 4 Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.) The 2x2 grid is as follows: Example 4: Input: [ "/\\", "\\/" ] Output: 5 Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.) The 2x2 grid is as follows: Example 5: Input: [ "//", "/ " ] Output: 3 Explanation: The 2x2 grid is as follows: Note: 1 <= grid.length == grid[0].length <= 30 grid[i][j] is either '/', '\', or ' '. """ ____ t___ _______ L.. c_ DisjointSet: ___ - """ unbalanced DisjointSet """ pi # dict ___ union x, y pi_x f.. x) pi_y f.. y) pi[pi_y] pi_x ___ find x # LHS self.pi[x] __ x n.. __ pi: pi[x] x __ pi[x] !_ x: pi[x] f.. pi[x]) r.. pi[x] c_ Solution: ___ regionsBySlashes grid: L..s.. __ i.. """ in 1 x 1 cell 3 possibilities ___ | | |___| ___ | /| |/__| ___ |\ | |__\| 4 regions in the ___ |\ /| |/_\| """ m, n l..(grid), l..(grid 0 ds DisjointSet() T, R, B, L r..(4) # top, right, bottom, left ___ i __ r..(m ___ j __ r..(n e grid[i][j] __ e __ "/" o. e __ " ": ds.union((i, j, B), (i, j, R ds.union((i, j, T), (i, j, L __ e __ "\\" o. e __ " ": # not elif ds.union((i, j, T), (i, j, R ds.union((i, j, B), (i, j, L # nbr __ i - 1 >_ 0: ds.union((i, j, T), (i-1, j, B __ j - 1 >_ 0: ds.union((i, j, L), (i, j-1, R # unnessary, half closed half open # if i + 1 < m: # ds.union((i, j, B), (i+1, j, T)) # if j + 1 < n: # ds.union((i, j, R), (i, j+1, L)) r.. l..(s..( ds.f.. x) ___ x __ ds.pi.k.. __ _______ __ _______ ... Solution().regionsBySlashes([ " /", "/ " ]) __ 2 ... Solution().regionsBySlashes([ "//", "/ " ]) __ 3
true
2901e2dbaab6f155dfd2d32feeed803ef2d07a5d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/674 Longest Continuous Increasing Subsequence.py
978
4.15625
4
#!/usr/bin/python3 """ Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. Example 2: Input: [2,2,2,2,2] Output: 1 Explanation: The longest continuous increasing subsequence is [2], its length is 1. Note: Length of the array will not exceed 10,000. """ ____ t___ _______ L.. c_ Solution: ___ findLengthOfLCIS nums: L.. i.. __ i.. """ pointer is sufficient """ __ n.. nums: r.. 0 ret 1 i 1 w.... i < l..(nums cur 1 w.... i < l..(nums) a.. nums[i] > nums[i-1]: cur += 1 i += 1 i += 1 ret m..(ret, cur) r.. ret
true
69accf57e5d5b8c3921c910a0f19e3b4def863dc
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/supplementary exercises/e0001-zip.py
857
4.53125
5
# zip(), lists, tuples # list is a sequence type # list can hold heterogenous elements # list is mutable - can expand, shrink, elements can be modified # list is iterable # tuple is a sequence type # tuple can hold heterogeneous data # tuple is immutable # tuple is iterable # Test case 1 - when iterables are of equal length def test_case1(): list1 = [ 1, 2, 3] list2 = [ 'a', 'b', 'c'] list3 = [ 'red', 'blue', 'green'] result = zip(list1, list2, list3) print(type(result)) for e in result: print(e) print(type(e)) # Test case 2 - when iterables are of unequal length def test_case2(): list1 = [ 1, 2, 3] list2 = [ 'a', 'b', 'c'] list3 = [ 'red', 'blue'] result = zip(list1, list2, list3) print(type(result)) for e in result: print(e) print(type(e)) test_case2()
true
438cb7633c606ebafa831e5a24a8ceb3ae2ba851
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-272-find-common-words.py
1,862
4.34375
4
""" Given two sentences that each contains words in case insensitive way, you have to check the common case insensitive words appearing in both sentences. If there are duplicate words in the results, just choose one. The results should be sorted by words length. The sentences are presented as list of words. Example: S = ['You', 'can', 'do', 'anything', 'but', 'not', 'everything'] ## ** ** T = ['We', 'are', 'what', 'we', 'repeatedly', 'do', 'is', 'not', 'an', 'act'] ## ** ** Result = ['do', 'not'] """ from typing import List def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]: """ Input: Two sentences - each is a list of words in case insensitive ways. Output: those common words appearing in both sentences. Capital and lowercase words are treated as the same word. If there are duplicate words in the results, just choose one word. Returned words should be sorted by word's length. """ lower_s1 = [e.lower() for e in sentence1 ] lower_s2 = [e.lower() for e in sentence2 ] result = list(set(lower_s1) & set(lower_s2)) return sorted(result, key=len) """ Approach: First, eliminate duplicates within each sentence. Second, use a intersection on both lists to find common elements. """ sentence1 = ['To', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'a', 'question'] sentence2 = ['To', 'strive', 'to', 'seek', 'to', 'find', 'and', 'not', 'to', 'yield'] sentence3 = ['No', 'two', 'persons', 'ever', 'to', 'read', 'the', 'same', 'book', 'You', 'said'] sentence4 = ['The', 'more', 'read', 'the', 'more', 'things', 'will', 'know'] sentence5 = ['be', 'a', 'good', 'man'] print(common_words(sentence1, sentence5))
true
ab296e2bb06b26e229bf476a06432826585dbbb5
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/2_dimensional_array_solution.py
1,011
4.375
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # --------------------------------------------------------------- # python best courses https://courses.tanpham.org/ # --------------------------------------------------------------- # Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. # The element value in the i-th row and j-th column of the array should be i*j. # Note : # i = 0,1.., m-1 # j = 0,1, n-1. # Input # Input number of rows: 3 # Input number of columns: 4 # Output # [[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]] row_num = int(input("Input number of rows: ")) col_num = int(input("Input number of columns: ")) multi_list = [[0 for col in range(col_num)] for row in range(row_num)] for row in range(row_num): for col in range(col_num): multi_list[row][col]= row*col print(multi_list)
true