blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
80906ba30bc751f48e177907ab2967803c269022
Vinod096/learn-python
/lesson_02/personal/chapter_5/12_Maximum_of_Two_Values.py
867
4.625
5
#Write a function named max that accepts two integer values as arguments and returns the #value that is the greater of the two. For example, if 7 and 12 are passed as arguments to #the function, the function should return 12. Use the function in a program that prompts the #user to enter two integer values. The program should display the value that is the greater #of the two. def value_1(): number_1 = int(input("enter value 1 : ")) return number_1 def value_2(): number_2 = int(input("enter value 2 : ")) return number_2 def max(value_1,value_2): if value_1 > value_2 : return value_1 else: return value_2 def main(): number_1 = value_1() number_2 = value_2() max_value = max(number_1,number_2) print("number 1 :",number_1) print("number 2 :",number_2) print("greater number :",max_value) main()
true
83b9e523b3ff90d47c7689f3293b77a16d05a965
Vinod096/learn-python
/lesson_02/personal/chapter_5/06_calories.py
1,078
4.65625
5
#A nutritionist who works for a fitness club helps members by evaluating their diets. As part #of her evaluation, she asks members for the number of fat grams and carbohydrate grams #that they consumed in a day. Then, she calculates the number of calories that result from #the fat, using the following formula: #calories from fat = fat grams * 9 #Next, she calculates the number of calories that result from the carbohydrates, using the #following formula: #calories from carbs= carb grams * 4 #The nutritionist asks you to write a program that will make these calculations. def fat(): fat_grams = float(input("Enter fat grams :")) calories_from_fat = fat_grams * 9 return calories_from_fat def carbohydrates(): carb_grams = float(input("Enter Carbohydrates :")) calories_from_carbs = carb_grams * 4 return calories_from_carbs def calculations(): C_fat = fat() C_carbohydrates = carbohydrates() print("Calories from fat is :{0:.2f}".format(C_fat)) print("calories from carbohydrates :{0:.2f}".format(C_carbohydrates)) calculations()
true
11a462649f8ebd34f0d29ab619e6d36bc98160af
Moandh81/python-self-training
/tuple/9.py
494
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program to find the repeated items of a tuple. mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "lion" , "zebra","duck" ,"bull", "sheep", "cat", "cow", "fox", "lion") frequency = {} for item in mytuple: if item.lower() not in frequency: frequency[item.lower()] = 1 else: frequency[item.lower()] = frequency[item.lower()] + 1 for key,value in frequency.items(): if frequency[key] > 1: print(key)
true
ac6d44000cce88e231a9a85d082c8538b44fd515
Moandh81/python-self-training
/datetime/32.py
272
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program to calculate a number of days between two dates. from datetime import date t1 = date(year = 2018, month = 7, day = 12) t2 = date(year = 2017, month = 12, day = 23) t3 = t1 - t2 print("t3 =", t3)
true
fee021a37c322579ad36109a92c914eaf4a809b7
Moandh81/python-self-training
/functions/1.py
657
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -* # Write a Python function to find the Max of three numbers. import re expression = r'[0-9]+' numberslist = [] number1 = number2 = number3 = "" while re.search(expression, number1) is None: number1 = input('Please input first number: \n') while re.search(expression, number2) is None: number2 = input('Please input second number: \n') while re.search(expression, number3) is None: number3 = input('Please input third number: \n') numberslist.append(number1) numberslist.append(number2) numberslist.append(number3) print(numberslist) print("the maximum number is {}".format(max(numberslist)))
true
4a43f7f498cda12296b75247c5b6d45941519527
Moandh81/python-self-training
/conditional-statements-and-loops/5.py
268
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program that accepts a word from the user and reverse it. word = input("Please input a word : \n") newword = "" i = len(word) while i > 0: newword = newword + word[i-1] i = i - 1 print(newword)
true
c78566301e0cc885f89c65310e9245fb5072dce1
Moandh81/python-self-training
/dictionary/24.py
517
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Write a Python program to create a dictionary from a string. Go to the editor # Note: Track the count of the letters from the string. # Sample string : 'w3resource' # Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1} txt = input('Please insert a string : \n') dictionary = {} for letter in txt: if letter not in dictionary.keys(): dictionary[letter] = 1 else: dictionary[letter] = dictionary[letter] + 1 print(dictionary)
true
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
650b2156b592b55355fcd441cdf6a29ba8760226
syurskyi/Python_Topics
/050_iterations_comprehension_generations/006_nested_comprehensions/examples/006_nested_comprehensions.py
1,954
4.75
5
# Nested Comprehensions # Just as with list comprehensions, we can nest generator expressions too: # A multiplication table: # Using a list comprehension approach first: # The equivalent generator expression would be: # We can iterate through mult_list: # But you'll notice that our rows are themselves generators! # o fully materialize the table we need to iterate through the row generators too: start = 1 stop = 10 mult_list = [ [i * j for j in range(start, stop+1)] for i in range(start, stop+1)] mult_list start = 1 stop = 10 mult_list = ( (i * j for j in range(start, stop+1)) for i in range(start, stop+1)) mult_list table = list(mult_list) table table_rows = [list(gen) for gen in table] table_rows # Nested Comprehensions # Of course, we can mix list comprehensions and generators. # In this modification, we'll make the rows list comprehensions, and retain the generator expression in the outer # comprehension: # Notice what is happening here, the table itself is lazy evaluated, i.e. the rows are not yielded until they # are requested - but once a row is requested, the list comprehension that defines the row will be entirely # evaluated at that point: start = 1 stop = 10 mult_list = ( [i * j for j in range(start, stop+1)] for i in range(start, stop+1)) for item in mult_list: print(item) # Let's try Pascal's triangle again: # Here's how we did it using a list comprehension: from math import factorial def combo(n, k): return factorial(n) // (factorial(k) * factorial(n-k)) size = 10 # global variable pascal = [ [combo(n, k) for k in range(n+1)] for n in range(size+1) ] # Let's try Pascal's triangle again: # # If we want to materialize the triangle into a list we'll need to do so ourselves: size = 10 # global variable pascal = ( (combo(n, k) for k in range(n+1)) for n in range(size+1) ) [list(row) for row in pascal]
true
f0deed5e91dc4476292f10ac0e544bd0a8290bb1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/746 Min Cost Climbing Stairs.py
1,291
4.125
4
#!/usr/bin/python3 """ On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. Note: cost will have a length in the range [2, 1000]. Every cost[i] will be an integer in the range [0, 999]. """ ____ t___ _______ L.. c_ Solution: ___ minCostClimbingStairs cost: L.. i.. __ i.. """ dp let F[i] be the cost to reach i-th stair F[i] = min F[i-2] + cost[i-2] F[i-1] + cost[i-1] """ n l..(cost) F [f__('inf') ___ _ __ r..(n+1)] F[0] 0 F[1] 0 ___ i __ r..(2, n+1 F[i] m..( F[i-2] + cost[i-2], F[i-1] + cost[i-1] ) r.. F[-1] __ _______ __ _______ ... Solution().minCostClimbingStairs([10, 15, 20]) __ 15
true
69fb9eab9782d4b53bbd781db80061561795fe8e
syurskyi/Python_Topics
/045_functions/013_switch_simulation/003.py
922
4.125
4
def add(x, to=1): return x + to def divide(x, by=2): return x / by def square(x): return x ** 2 def invalid_op(x): raise Exception("Invalid operation") def perform_operation(x, chosen_operation, operation_args=None): # If operation_args wasn't provided (i.e. it is None), set it to be an empty dictionary operation_args = operation_args or {} ops = { "add": add, "divide": divide, "square": square } chosen_operation_function = ops.get(chosen_operation, invalid_op) return chosen_operation_function(x, **operation_args) def example_usage(): x = 1 x = perform_operation(x, "add", {"to": 4}) # Adds 4 print(x) x = perform_operation(x, "add") # Adds 1 since that's the default for 'add' x = perform_operation(x, "divide", {"by": 2}) # Divides by 2 x = perform_operation(x, "square") # Squares the number example_usage()
true
0aa08a662cb93ae1b78a565535806c5f649c40c2
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/triangle_types_solution.py
645
4.125
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to check a triangle is equilateral, isosceles or scalene. # Note : # An equilateral triangle is a triangle in which all three sides are equal. # A scalene triangle is a triangle that has three unequal sides. # An isosceles triangle is a triangle with (at least) two equal sides. print("Input lengths of the triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) if x == y == z: print("Equilateral triangle") elif x != y != z: print("Scalene triangle") else: print("isosceles triangle")
true
9668ed9b59dffd211b71d671e99bff049ca83215
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/232 Implement Queue using Stacks.py
1,349
4.28125
4
""" Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). """ __author__ 'Daniel' c_ Queue: ___ - in_stk # list out_stk # list ___ push x """ :type x: int :rtype: None """ in_stk.a..(x) ___ pop """ :rtype: None """ __ n.. out_stk: w.... in_stk: out_stk.a..(in_stk.pop out_stk.p.. ) ___ peek """ :rtype: int """ __ n.. out_stk: w.... in_stk: out_stk.a..(in_stk.pop r.. out_stk[-1] ___ empty """ :rtype: bool """ r.. n.. out_stk a.. n.. in_stk
true
46b95cecb37be01d2c4ced998e143f9f08a7b9b2
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-13-convert-dict-to-namedtuple-json.py
2,029
4.1875
4
""" TASK DESCRIPTION: Write a function to convert the given blog dict to a namedtuple. Write a second function to convert the resulting namedtuple to json. Here you probably need to use 2 of the _ methods of namedtuple :) """ ____ c.. _______ n.. ____ c.. _______ O.. ____ d__ _______ d__ _______ j__ # Q: What is the difference between tuple and list? blog d.. name='PyBites', founders=('Julian', 'Bob'), started=d__ y.._2016, m.._12, d.._19), tags= 'Python', 'Code Challenges', 'Learn by Doing' , location='Spain/Australia', site='https://pybit.es') """ INITIAL CONSIDERATIONS: How could resulting JSON look like? Question is how to serialize datetime? j = { "name": "PyBites", "founders": ["Julian", "Bob"], "started": { "year": "2016", "month": "12", "day": "19" }, "tags": ["Python", "Code Challenges", "Learn by Doing"], "location": "Spain/Australia", "site": "https://pybit.es" } """ ### --------- My solution ------------- # define namedtuple here Blog n..('Blog', 'name founders started tags location site') ___ dict2nt(dict_ b Blog(dict_.g.. 'name'), dict_.g.. 'founders'), dict_.g.. 'started'), dict_.g.. 'tags'), dict_.g.. 'location'), dict_.g.. 'site' r.. b ___ nt2json(nt j__.d.. ) b ? ? # Q: How to serialize datetime object? # https://code-maven.com/serialize-datetime-object-as-json-in-python # https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable/36142844#36142844 print(j__.d..O..(b._asdict, default=s.., indent=4 ### ---------- PyBites original solution --------------- # define namedtuple here pybBlog n..('pybBlog', blog.keys # https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters ___ pyb_dict2nt(dict_ r.. pybBlog($$? ___ pyb_nt2json(nt nt ?._replace(started=s..(?.started r.. j__.d..?._asdict
true
1af8cd8a831f0b63b8c77d2ff35f4ec3e6a1b3f8
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 60 - MergeSortLists.py
1,158
4.15625
4
# Merge Sorted Lists # Question: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # Solutions: class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param two ListNodes # @return a ListNode def mergeTwoLists(self, l1, l2): dummy = ListNode(0) pointer = dummy while l1 !=None and l2 !=None: if l1.val<l2.val: pointer.next = l1 l1 = l1.next else: pointer.next = l2 l2 = l2.next pointer = pointer.next if l1 == None: pointer.next = l2 else: pointer.next = l1 return dummy.next def printll(self, node): while node: print ( node.val ) node = node.next if __name__ == '__main__': ll1, ll1.next, ll1.next.next = ListNode(2), ListNode(3), ListNode(5) ll2, ll2.next, ll2.next.next = ListNode(4), ListNode(7), ListNode(15) Solution().printll( Solution().mergeTwoLists(ll1,ll2) )
true
56ff56c9d7977a59184e97c87a15187edbd1a63f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/520 Detect Capital.py
1,228
4.375
4
#!/usr/bin/python3 """ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital if it has more than one letter, like "Google". Otherwise, we define that this word doesn't use capitals in a right way. Example 1: Input: "USA" Output: True Example 2: Input: "FlaG" Output: False Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. """ c_ Solution: ___ detectCapitalUse word: s..) __ b.. """ Two passes is easy How to do it in one pass """ __ n.. word: r.. T.. head_upper word[0].isupper() # except for the head has_lower F.. has_upper F.. ___ w __ word 1| __ w.isupper has_upper T.. __ has_lower o. n.. head_upper: r.. F.. ____ has_lower T.. __ has_upper: r.. F.. r.. T..
true
d30652b267569247f9d3c6a1f20ad03f3f902250
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTesting-master/Proj4/ListsAndTuples/listAndTuples.py
2,218
4.375
4
______ ___ ______ timeit # https://www.youtube.com/watch?v=NI26dqhs2Rk # Tuple is a smaller faster alternative to a list # List contains a sequence of data surrounded by brackets # Tuple contains a squence of data surrounded by parenthesis """ Lists can have data added, removed, or changed Tuples cannot change. Tuples can be made quickly. """ # List example prime_numbers _ [2, 3, 5, 7, 11, 13, 17] # Tuple example perfect_squares _ (1, 4, 9, 16, 25, 36) # Display lengths print("# Primes = ", le.(prime_numbers)) print("# Squares = ", le.(perfect_squares)) # Iterate over both sequences ___ p __ prime_numbers: print("Prime: ", p) ___ n __ perfect_squares: print("Square: ", n) print("") print("List Methods") print(dir(prime_numbers)) print(80*"-") print("Tuple methods") print(dir(perfect_squares)) print() print(dir(___)) print(help(___.getsizeof)) print() list_eg _ [1, 2, 3, "a", "b", "c", T.., 3.14159] tuple_eg _ (1, 2, 3, "a", "b", "c", T.., 3.14159) print("List size = ", ___.getsizeof(list_eg)) print("Tuple size = ", ___.getsizeof(tuple_eg)) print() list_test _ timeit.timeit(stmt_"[1, 2, 3, 4, 5]", number_1000000) tuple_test _ timeit.timeit(stmt_"(1, 2, 3, 4, 5)", number_1000000) print("List time: ", list_test) print("Tuple time: ", tuple_test) print() ## How to make tuples empty_tuple _ () test0 _ ("a") test1 _ ("a",) # To make a tuple with just one element you need to have a comma at the end test2 _ ("a", "b") test3 _ ("a", "b", "c") print(empty_tuple) print(test0) print(test1) print(test2) print(test3) print() # How to make tuples part 2 test1 _ 1, test2 _ 1, 2 test3 _ 1, 2, 3 print(test1) print(test2) print(test3) print() # (age, country, knows_python) survey _ (27, "Vietnam", T..) age _ survey[0] country _ survey[1] knows_python _ survey[2] print("Age =", age) print("Country =", country) print("Knows Python?", knows_python) print() survey2 _ (21, "Switzerland", F..) age, country, knows_python _ survey2 print("Age =", age) print("Country =", country) print("Knows Python?", knows_python) print() # Assigns string to variable country country _ ("Australia") # Here country is a tuple, and it doesnt unpack contents into variable country _ ("Australia",)
true
c035fcefec027a5b8e1c619b49d09c7c96cbc330
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-169-simple-length-converter.py
1,245
4.34375
4
''' Your task is to complete the convert() function. It's purpose is to convert centimeters to inches and vice versa. As simple as that sounds, there are some caveats: convert(): The function will take value and fmt parameters: value: must be an int or a float otherwise raise a TypeError fmt: string containing either "cm" or "in" anything else raises a ValueError. returns a float rounded to 4 decimal places. Assume that if the value is being converted into centimeters that the value is in inches and centimeters if it's being converted to inches. That's it! ''' ___ convert(value: f__, fmt: s..) __ f__: """Converts the value to the designated format. :param value: The value to be converted must be numeric or raise a TypeError :param fmt: String indicating format to convert to :return: Float rounded to 4 decimal places after conversion """ __ t..(value) __ i.. o. t..(value) __ f__: __ fmt.l.. __ "cm" o. fmt.l.. __ "in": __ fmt.l.. __ "cm": result value*2.54 r.. r..(result,4) ____ result value*0.393700787 r.. r..(result, 4) ____ r.. V... ____ r.. T.. print(convert(60.5, "CM"
true
0e1f60a4dd71d99753e8a19d3f767d8d2815615d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/768 Max Chunks To Make Sorted II.py
1,673
4.40625
4
#!/usr/bin/python3 """ This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8. Given an array arr of integers (not necessarily distinct), 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 = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. Example 2: Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. Note: arr will have length in range [1, 2000]. arr[i] will be an integer in range [0, 10**8]. """ ____ t___ _______ L.. ____ c.. _______ d.., d.. c_ Solution: ___ maxChunksToSorted arr: L.. i.. __ i.. """ not necessarily distinct sort and assign index For the smae element, the right ones should get larget assigned index """ A s..(arr) hm d..(d..) ___ i, e __ e..(A hm[e].a..(i) proxy # list ___ e __ arr: proxy.a..(hm[e].popleft ret 0 cur_max_idx 0 ___ i, e __ e..(proxy cur_max_idx m..(cur_max_idx, e) __ cur_max_idx __ i: ret += 1 r.. ret
true
2a941e251d78633d70caf05e60efa864cc49aba9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/701 Insert into a Binary Search Tree.py
1,190
4.375
4
#!/usr/bin/python3 """ Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. For example, Given the tree: 4 / \ 2 7 / \ 1 3 And the value to insert: 5 You can return this binary search tree: 4 / \ 2 7 / \ / 1 3 5 This tree is also valid: 5 / \ 2 7 / \ 1 3 \ 4 """ # Definition for a binary tree node. c_ TreeNode: ___ - , x val x left N.. right N.. c_ Solution: ___ insertIntoBST root: TreeNode, val: i.. __ TreeNode: __ n.. root: r.. TreeNode(val) __ root.val < val: root.right insertIntoBST(root.right, val) ____ root.val > val: root.left insertIntoBST(root.left, val) ____ r.. r.. root
true
f50b7d8beae1763ff2665416301bec37eff8fc53
syurskyi/Python_Topics
/050_iterations_comprehension_generations/009_permutations/examples/009_permutations.py
1,745
4.46875
4
# Permutations # In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence # or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. # These differ from combinations, which are selections of some members of a set where order is disregarded. # We can create permutations of length n from an iterable of length m (n <= m) using the permutation function: # As you can see all the permutations are, by default, the same length as the original iterable. # We can create permutations of smaller length by specifying the r value: # The important thing to note is that elements are not 'repeated' in the permutation. # But the uniqueness of an element is not based on its value, but rather on its position in the original iterable. # This means that the following will yield what looks like the same permutations when considering the values of # the iterable: l1 = 'abc' list(itertools.permutations(l1)) list(itertools.permutations(l1, 2)) list(itertools.permutations('aaa')) list(itertools.permutations('aba', 2)) # Combinations # Combinations refer to the combination of n things taken k at a time without repetition. To refer to combinations in # which repetition is allowed, the terms k-selection,[1] k-multiset,[2] or k-combination with repetition are often used. # itertools offers both flavors - with and without replacement. # Let's look at a simple example with replacement first: # As you can see (4, 3) is not included in the result since, as a combination, it is the same as (3, 4) - # order is not important. list(itertools.combinations([1, 2, 3, 4], 2)) list(itertools.combinations_with_replacement([1, 2, 3, 4], 2))
true
c3cac517a34075d13cc9839c5aafffab20eefd1d
syurskyi/Python_Topics
/045_functions/007_lambda/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 67 sum_even_values.py
566
4.21875
4
# Sum Even Values Solution # # I define a function called sum_even_values which accepts any number of arguments, thanks to *args # I grab the even numbers using the generator expression (arg for arg in args if arg % 2 == 0) # (could also use a list comp) # I pass the even numbers I extracted into sum() and return the value # The default start value of sum() # is 0, so I don't have to do anything special to get it to return 0 if there are no even numbers! def sum_even_values(*args): return sum(arg for arg in args if arg % 2 == 0)
true
e68fa28abb8eb130145171dbbaadced13f473c6d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/953 Verifying an Alien Dictionary.py
1,996
4.21875
4
#!/usr/bin/python3 """ In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. Example 3: Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). Note: 1 <= words.length <= 100 1 <= words[i].length <= 20 order.length == 26 All characters in words[i] and order are english lowercase letters. """ ____ t___ _______ L.. c_ Solution: ___ isAlienSorted words: L..[s..], order: s..) __ b.. h # dict ___ i, c __ e..(order h[c] i ___ i __ r..(1, l.. ? __ cmp(words[i], words[i-1], h) __ -1: r.. F.. r.. T.. ___ cmp w1, w2, h ___ c1, c2 __ z..(w1, w2 __ h[c1] < h[c2]: r.. -1 ____ h[c1] > h[c2]: r.. 1 __ l..(w1) __ l..(w2 r.. 0 ____ l..(w1) > l..(w2 r.. 1 ____ r.. -1 __ _______ __ _______ ... Solution().isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz") __ T..
true
c7fde44dbdbdd8fbf0a8f75bc98819f46a6d2dd2
Nunziatellanicolepalarymzai/Python-104
/mean.py
883
4.375
4
# Python program to print # mean of elements # list of elements to calculate mean import csv with open('./height-weight.csv', newline='') as f: reader = csv.reader(f) #csv.reader method,reads and returns the current row and then moves to the next file_data = list(reader) #list(reader) adds the data to the list file_data.pop(0) #to remove the title from the data print(file_data) # sorting data to get the height of people. new_data=[] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(float(n_num)) #Then create a empty list named new_data . #Then use a for loop on file_data to get the elements inside the nested lists #and append them to the new_data list. # #getting the mean n = len(new_data) total =0 for x in new_data: total += x mean = total / n # print("Mean / Average is: " + str(mean))
true
34b74af222fda40f35d744e2909cde08df0f3092
ravis3517/i-neuron-assigment-and-project-
/i neuron_python_prog_ Assignment_3.py
1,845
4.34375
4
#!/usr/bin/env python # coding: utf-8 # 1. Write a Python Program to Check if a Number is Positive, Negative or Zero # In[25]: num = float(input("Enter a number: ")) if num >0: print("positive") elif num <0 : print("negative") else: print(" number is zero") # 2. Write a Python Program to Check if a Number is Odd or Even? # In[26]: num=int(input("enter the number:\n")) if (num %2==0): print("The number is even") else: print("the number is odd") # 3.Write a Python Program to Check Leap Year? # A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400 # In[27]: # To enter year by user year=int(input("Enter the year:\n")) # Leap Year Check if year % 4 == 0 and year % 100 != 0: print(year, "is a Leap Year") elif year % 100 == 0: print(year, "is not a Leap Year") elif year % 400 ==0: print(year, "is a Leap Year") else: print(year, "is not a Leap Year") # Write a Python Program to Check Prime Number? # In[28]: #test all divisors from 2 through n-1 (Skip 1 and n since prime number is divided by 1 and n ) num=10 for i in range(2,num): ## it will test till n-1 i.e till 9 if num % i == 0: print( num , " is Not prime") break else : print( num ," is a prime") # Write a Python Program to Print all Prime Numbers in an Interval of 1-10000? # In[29]: # Python program to print all # prime number in an interval # number should be greater than 1 first_number = 1 last_number = 10000 for i in range(first_number ,last_number +1): if i>1: for j in range(2,i): if i%j==0: break else: print(i)
true
07540d509c99f96db7fcc7f7362a36f5dc52d36d
bowie2k3/cos205
/COS-205_assignment4b_AJ.py
683
4.5
4
# Write a program that counts the number of words in a text file. # the program should print out [...] the number of words in the file. # Your program should prompt the user for the file name, which # should be stored at the same location as the program. # It should consider anything that is separated by white space or # new line on either side of a contiguous group of characters or # character as a word. def main(): fname = input("Please enter the filename: ") infile = open(fname, "r") data = infile.read() stripnl = data.replace("\n", " ") words = stripnl.split(" ") count = len(words) print("The number of words in the file is: ", count) main()
true
b6d35f31562d97ec2fe4c6d9a1d349d23a45e7ea
jmmalnar/python_projects
/primes.py
1,896
4.40625
4
import unittest # Find all the prime numbers less than a given integer def is_prime(num): """ Iterate from 2 up to the (number-1). Assume the number is prime, and work through all lower numbers. If the number is divisible by ANY of the lower numbers, then it's not prime """ prime_status = True # 1, by definition, is not a prime number, so lets account for that directly if num == 1: prime_status = False return prime_status for i in range(2, num): mod = num % i if mod == 0: prime_status = False break return prime_status def find_primes(num): primes = [] for n in range(1, num): prime_status = is_prime(n) if prime_status: primes.append(n) return primes ######## # TEST # ######## class IsPrimesTests(unittest.TestCase): def test_19_should_be_prime(self): """Verify that inputting a prime number into the is_prime method returns true""" self.assertEqual(is_prime(19), True) def test_20_should_not_be_primer(self): """Verify that inputting a non-prime number into the is_prime method returns false""" self.assertEqual(is_prime(20), False) def test_1_should_not_be_prime(self): """Verify that inputting 1 into the is_prime method returns false""" self.assertEqual(is_prime(1), False) class FindPrimesTests(unittest.TestCase): def test_primes_to_20(self): """Verify that all of the correct primes less than 20 are returned""" primes = find_primes(20) self.assertEqual(primes, [2, 3, 5, 7, 11, 13, 17, 19]) def test_1_should_not_be_prime(self): """Verify that nothing is returned when you try and find all primes under 1""" primes = find_primes(1) self.assertEqual(primes, []) if __name__ == '__main__': unittest.main()
true
69d63e236fd5585208ec5bebab45137c260c3562
lmhavrin/python-crash-course
/chapter-seven/deli.py
536
4.4375
4
# Exercise: 7-8 Deli # A for loop is useful for looping through a list # A while loop is useful for looping through a list AND MODIFYING IT sandwich_orders = ["turkey", "roast beef", "chicken", "BLT", "ham"] finished_sandwiches = [] while sandwich_orders: making_sandwich = sandwich_orders.pop() print("I made your " + making_sandwich + " sandwich.") finished_sandwiches.append(making_sandwich) print("\n Here are the list of sandwiches finished: ") for sandwich in finished_sandwiches: print("-" + sandwich.title())
true