blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0ce57fc5296a09864fb1e75080a20c684bceef98
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/car_truck_suv_demo.py
1,521
4.1875
4
# This program creates a Car object, a truck object, and an SUV object import vehicles import pprint def main(): # Create a Car object car = vehicles.Car('Bugatti', 'Veyron', 0, 3000000, 2) # Create a truck object truck = vehicles.Truck('Dodge', 'Power Wagon', 0, 57000, '4WD') # Create an SUV object suv = vehicles.SUV('Jeep', 'Wrangler', 200000, 5000, 4) print('VEHICLE INVENTORY') print('=================') # Display the vehicles data print('\nmake', car.get_make()) print('model', car.get_model()) print('mileage', car.get_mileage()) print(f'price {car.get_price():.2f}') print('doors', car.get_doors()) print('\nmake', truck.get_make()) print('model', truck.get_model()) print('mileage', truck.get_mileage()) print(f'price {truck.get_price():.2f}') print('doors',truck.get_drive_type()) print('\nmake', suv.get_make()) print('model', suv.get_model()) print('mileage', suv.get_mileage()) print(f'price {suv.get_price():.2f}') print('doors', suv.get_pass_cap()) # shows cool info about the things # print(help(vehicles.SUV)) # shows if an object is an instance of a class print(isinstance(suv, vehicles.Automobile)) # shows if an object is a subclass of another print(issubclass(vehicles.SUV, vehicles.Automobile)) # print or set object as the dictionary of the items bob = suv.__dict__ pprint.pprint(bob, sort_dicts = False) main()
false
d2e06b65113045bf009e371c53cc73750f8184a7
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Recursion/Practice/7.py
1,181
4.21875
4
""" 7. Recursive Power Method Design a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a nonnegative integer. """ # define main def main(): # Establish vars int1 = int(input("Enter the first integer: ")) int2 = int(input("Enter the second integer: ")) # pass to function exp(int1, int2, 1) # define exponent # def exp(x, y, z, a): # if z is greater than the exponent then print the formatted number # if z > y: # print(f'{a:,.2f}') # # If not cal lthe function again passing z, y and z plus 1 and the total times the base number # else: # return exp(x, y, z + 1, a * x) # A better way less lines, simpler def exp(x, y, a): # While y is greater than 0 call the function again passing x, y - 1 and a (the total) times the base number while y > 0: return exp(x, y - 1, a * x) print(f'{a:,.2f}') # call main main() # 7. # def power(x,y): # if y == 0: # return 1 # else: # return x * power(x, y - 1) # print(power(3,3))
true
f149ee1bf7a78720f53a8688d83d226cb00dc5eb
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/Cars.py
2,383
4.8125
5
""" 2. Car Class Write a class named Car that has the following data attributes: • __year_model (for the car’s year model) • __make (for the make of the car) • __speed (for the car’s current speed) The Car class should have an __init__ method that accept the car’s year model and make as arguments. These values should be assigned to the object’s __year_model and __make data attributes. It should also assign 0 to the __speed data attribute. The class should also have the following methods: • accelerate The accelerate method should add 5 to the speed data attribute each time it is called. • brake The brake method should subtract 5 from the speed data attribute each time it is called. • get_speed The get_speed method should return the current speed. Next, design a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it. """ # define the class of cars class Cars: # define the init with all the variables def __init__(self, year, make, model, speed): self.__year = year self.__make = make self.__model = model self.__speed = speed # def setting the year of the car def set_year(self, year): self.__year = year # def function to set the make of the car def set_make(self, make): self.__make = make # def function to set the model of the car def set_model(self, model): self.__model = model # def function to accelerate def accelerate(self): self.__speed += 5 return self.__speed # def function to begin braking def brake(self): self.__speed -= 5 return self.__speed # define a function to get the speed def get_speed(self): return self.__speed # return the year def get_year(self): return self.__year # returns the make def get_make(self): return self.__make # return the model def get_model(self): return self.__model
true
eaa53c820d135506b1252749ab50b320d11d53b5
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/5 - RetailItem.py
1,427
4.625
5
""" 5. RetailItem Class Write a class named RetailItem that holds data about an item in a retail store. The class should store the following data in attributes: item description, units in inventory, and price. Once you have written the class, write a program that creates three RetailItem objects and stores the following data in them: Description Units in Inventory Price Item #1 Jacket 12 59.95 Item #2 Designer Jeans 40 34.95 Item #3 Shirt 20 24.95 """ # import the important things import RetailItem # establish the dictionary with the data item_dict = {1 : { 'description' : 'Jacket', 'units' : 12, 'price' : 59.95}, 2 : { 'description' : 'Designer Jeans', 'units' : 40, 'price' : 34.95}, 3 : { 'description' : 'Shirt', 'units' : 20, 'price' : 24.95}} # define the main function def main(): # set the variable to call the class and use dictionary info to populate it item1 = RetailItem.RetailItem(item_dict[1]['description'], item_dict[1]['units'], item_dict[1]['price']) item2 = RetailItem.RetailItem(item_dict[2]['description'], item_dict[2]['units'], item_dict[2]['price']) item3 = RetailItem.RetailItem(item_dict[3]['description'], item_dict[3]['units'], item_dict[3]['price']) # display the data print(item1, item2, item3) # call main main()
true
b046b95c144bbe51ac2c77b5363814b8b5d2b5cc
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/6.py
503
4.46875
4
# 6. Celsius to Fahrenheit Table # Write a program that displays a table of the Celsius temperatures 0 through 20 and theirFahrenheit equivalents. # The formula for converting a temperature from Celsius toFahrenheit is # F = (9/5)C + 32 where F is the Fahrenheit temperature and C is the Celsius temperature. # Your programmust use a loop to display the table. fahr = [((9/5) * cel + 32) for cel in range(21)] for x, y in enumerate(fahr): print(f'{x:} celcius is {y:.2f} fahrenheit.')
true
9e6bdd3adc3e850240f3c9a94dd766ecdd4abe97
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/FileExercises/9.py
1,013
4.28125
4
# 9. Exception Handing # Modify the program that you wrote for Exercise 6 so it handles the following exceptions: # • It should handle any IOError exceptions that are raised when the file is opened and datais read from it. # Define counter count = 0 # Define total total = 0 try: # Display first 5 lines # Open the file infile = open("numbers.txt", 'r') # Set readline line = infile.readline() while line != '': # Convert line to a float display = int(line) # Increment count and total count += 1 total += display # Format and display data print(display) # Read the next line line = infile.readline() print(f"\n The average of the lines is {total/count:.2f}") # If file doesn't exist, show this error message except: print(f"\n An error occured trying to read numbers.txt") if count > 0: print(f" to include line {count:} \n")
true
2118efbe7e15e295f6ceea7b4a4c26696b22edb1
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Unit Testing and Multithreading/MultiThreading/Multithreadingclassdemo1/multithreading.py
1,434
4.15625
4
''' RUnning things concurrently is known as multithreading Running things in parallel is known as multiprocessing I/O bound tasks - Waiting for input and output to be completed reading and writing from file system, network operations. These all benefit more from threading You get the illusion of running code at the same time, however other code starts running while other code is waiting CPU bound tasks - Good for number crunching Using CPU Data Crunching These benefit more from multiprocessing and running in parallel Using multiprocessing might be slower if you have overhead from creating and destroying files. ''' import threading import time start = time.perf_counter() def do_something(): print('Sleeping 1 second....') time.sleep(1) print('Done Sleeping....') # how we did it # do_something() # do_something() # create threads for new way t1 = threading.Thread(target=do_something) t2 = threading.Thread(target=do_something) #start the thread t1.start() t2.start() # make sure the threads complete before moving on to calculate finish time: t1.join() t2.join() finished = time.perf_counter() print(f'Our program finished in {finished - start:.6f} seconds.')
true
f1923bf1fc1a3ab94a7f5d32c929cd6914fc7605
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Test Stuff/First Test/shapes1.py
2,305
4.25
4
class GeometricObject: def __init__(self, color = "green", filled = True): self.color = color self.filled = filled def getColor(self): return self.color def setColor(self, color): self.color = color def isFilled(self): return self.filled def setFilled(self, filled): self.filled = filled def toString(self): return "color: " + self.color + " and filled: " + str(self.filled) ''' (The Triangle class) Design a class named Triangle that extends the GeometricObject class defined below. The Triangle class contains: - Three float data fields named side1, side2, and side3 to denote the three sides of the triangle. - A constructor that creates a triangle with the specified side1, side2, and side3 with default values 1.0. - The accessor methods for all three data fields. - A method named getArea() that returns the area of this triangle. - A method named getPerimeter() that returns the perimeter of this triangle. - A method named __str__() that returns a string description for the triangle. ''' class TriangleObject: def __init__(self, color = "green", filled = True, side1 = 1.0, side2 = 1.0, side3 = 1.0): super().__init__(color, filled) self.side1 = side1 self.side2 = side2 self.side3 = side3 def set_side1(self, side1): self.side1 = side1 def set_side2(self, side2): self.side2 = side2 def set_side3(self, side3): self.side3 = side3 def get_side1(self, side1): return self.side1 def get_side2(self, side2): return self.side2 def get_side3(self, side3): return self.side3 def getPerimeter(self): self.perimeter = (self.side1 + self.side2 + self.side3)/2 return self.perimeter def getArea(self): self.area = (self.perimeter * (self.perimeter - self.side1) * (self.perimeter - self.side2) * (self.perimeter - self.side3)) ** (1/2.0) return self.area def __str__(self): return f'A triangle is a 3 sided shape. The current sides have a length of {self.side1}, {self.side2}, and {self.side3}'
true
cd2b8237503c74dfc7864dd4ec64d7f334c9ecb0
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/8 - trivia.py
2,521
4.4375
4
""" 8. Trivia Game In this programming exercise you will create a simple trivia game for two players. The program will work like this: • Starting with player 1, each player gets a turn at answering 5 trivia questions. (There should be a total of 10 questions.) When a question is displayed, 4 possible answers are also displayed. Only one of the answers is correct, and if the player selects the correct answer, he or she earns a point. • After answers have been selected for all the questions, the program displays the number of points earned by each player and declares the player with the highest number of points the winner. To create this program, write a Question class to hold the data for a trivia question. The Question class should have attributes for the following data: • A trivia question • Possible answer 1 • Possible answer 2 • Possible answer 3 • Possible answer 4 • The number of the correct answer (1, 2, 3, or 4) The Question class also should have an appropriate __init__ method, accessors, and mutators. The program should have a list or a dictionary containing 10 Question objects, one for each trivia question. Make up your own trivia questions on the subject or subjects of your choice for the objects. """ question_dict = {"Blue, Black or Red?" : ['Blue', 'Red', 'Clear', 'Black'], "Yes or No?" : ['Yes', 'Maybe', 'True', 'No'], "Laptop or Desktop?" : ['Cell Phone', 'Tablet', 'Laptop', 'Desktop']} import trivia import random def main(): global question_dict questions = trivia.Trivia() questions.bulk_add(question_dict) for key in questions.get_questions(): print(key) # print(questions.get_questions()[key]) answerlist = [] answerlist2 = [] for i in questions.get_questions()[key]: answerlist.append(i) answerlist2.append(i) random.shuffle(answerlist2) print("1", answerlist) print("2", answerlist2) count = 0 for i in answerlist2: print(f"Number {count}: {i}") count += 1 choice = int(input("Enter the number choice for your answer: ")) if answerlist[3] == answerlist2[choice]: print("You got it right!") else: print("You got it wrong!") main()
true
1658b421c637ec8ab3524446baccd8f30da4470c
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Lists/tuples.py
394
4.25
4
# tuples are like an immutable list my_tuple = (1, 2, 3, 4, 5) print(my_tuple) # printing items in a tuple names = ('Holly', 'Warren', 'Ashley') for n in names: print(n) for i in range(len(names)): print (names[i]) # Convert between a list and a tuple listA = [2, 4, 5, 1, 6] type(listA) tuple(listA) type(listA) tupA = tuple(listA) type(tupA)
false
8b72f14467bc40821bc0fb0c7c2ad9f05be58cd0
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 3.py
2,460
4.46875
4
""" 3. Person and Customer Classes Write a class named Person with data attributes for a person’s name, address, and telephone number. Next, write a class named Customer that is a subclass of the Person class. The Customer class should have a data attribute for a customer number and a Boolean data attribute indicating whether the customer wishes to be on a mailing list. Demonstrate an instance of the Customer class in a simple program. """ import assets import pprint pppl_lst = [] cust_lst = [] def main(): global pppl_lst, cust_lst pppl_num = int(input('Enter the number of people you need to add: ')) setthelist(pppl_num) print("Not Customers: ") print_list(pppl_lst) print("Customers: ") print_list(cust_lst) def setthelist(theamount): global pppl_lst, cust_lst for i in range(theamount): print("Person", i+1) customerinput = int(input('Is this person a customer? 1 for yes 0 for no: ')) if customerinput == 1: name = input('Enter the persons name: ') address = input('Enter the address: ') phone = input('Enter the phone number for the person: ') cust_num = int(input('Enter the customer number: ')) mail = 2 while mail != 0 and mail != 1: mail = int(input('Does the customer want to be on the mailing list? 1 = yes 0 = no: ')) print('mail', mail) customer = assets.Customer(name, address, phone, cust_num, bool(mail)) cust_lst.append(customer) elif customerinput == 0: name = input('Enter the persons name: ') address = input('Enter the address: ') phone = input('Enter the phone number for the person: ') notcustomer = assets.Person(name, address, phone) pppl_lst.append(notcustomer) def print_list(listss): if listss is pppl_lst: for i in listss: print('Name: ', i.get_name()) print('Address: ', i.get_address()) print('Phone: ', i.get_phone()) elif listss is cust_lst: for i in listss: print('Name: ', i.get_name()) print('Address: ', i.get_address()) print('Phone: ', i.get_phone()) print('Customer Number: ', i.get_cust_num()) print('Is on mailing address: ', i.get_mail()) main()
true
ab93e5065c94a86f8ed6c812a3292100925a1bb5
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/IfElsePractice/5.py
1,575
4.4375
4
# 5. Color Mixer # The colors red, blue, and yellow are known as the primary colors because they cannot be # made by mixing other colors. When you mix two primary colors, you get a secondary color, # as shown here: # When you mix red and blue, you get purple. # When you mix red and yellow, you get orange. # When you mix blue and yellow, you get green. # Design a program that prompts the user to enter the names of two primary colors to mix. # If the user enters anything other than “red,” “blue,” or “yellow,” the program should display an # error message. Otherwise, the program should display the name of the secondary color that results. def main(): color_one = color() checker(color_one) color_two = color() checker(color_two) blender(color_one, color_two) def checker(color): if color == "red" or color == "blue" or color == "yellow": print("You chose", color) else: print("Choose one of the primary colors!") exit() def color(): return input("Enter 'red', 'blue', or 'yellow'. ") def blender(first, second): if (first == "red" or second == "red") and (first == "blue" or second == "blue"): print("Your blend is purple") elif (first == "yellow" or second == "yellow") and (first == "blue" or second == "blue"): print("Your blend is green") elif (first == "red" or second == "red") and (first == "yellow" or second == "yellow"): print("Your blend is orange") else: print("Your colors were the same") main()
true
d63f59488d65ba81d647da41c15424a0901d18b4
DimitrisMaskalidis/Python-2.7-Project-Temperature-Research
/Project #004 Temperature Research.py
1,071
4.15625
4
av=0; max=0; cold=0; count=0; pl=0; pres=0 city=raw_input("Write city name: ") while city!="END": count+=1 temper=input("Write the temperature of the day: ") maxTemp=temper minTemp=temper for i in range(29): av+=temper if temper<5: pl+=1 if temper>maxTemp: maxTemp=temper if temper<minTemp: minTemp=temper temper=input("Write the temperature of the day: ") print "The differance between highest and lowest temperature is",maxTemp-minTemp av=av/30.0 if count==1: max=av if av>max: max=av maxname=city if av>30: pres+=1 if pl==30: cold+=1 pl=0 city=raw_input("Write city name: ") print "The percentage of the cities with average temperature more than 30 is",count/pres*100,"%" print "The city with the highest average temperature is",maxname,"with",max,"average temperature" if cold>0: print "There is a city with temperature below 5 every day"
true
4d1e19c830d0f41e51c4837a8792b8a054ee6655
viniciuskurt/LetsCode-PracticalProjects
/1-PythonBasics/aula04_Operadores.py
1,578
4.40625
4
''' OPERADORES ARITMETICOS Fazem operações aritméticas simples: ''' print('OPERADORES ARITMÉTICOS:\n') print('+ soma') print('- subtração') print('* multiplicacao') print('/ divisão') print('// divisão inteira') #não arredonda o resultado da divisão, apenas ignora a parte decimal print('** potenciação') print('% resto da divisão\n') x = 2 y = 5 m = x * y print('x * y = ',m) s = x + y print('x + y = ',s) sub = x - y print('x - y = ',sub) d = x / y print('y / x = ',d) di = x // y print('x // y = ',di) p = x ** y print('x ** y = ',p) rd = x % y print('x % y = ',rd) print('--' *30 ) print('OPERADORES LÓGICOS:\n') print('OR - resultado Verdadeiro se UMA ou AMBAS expressões for verdadeira') print('AND - resultado Verdadeiro somente se AMBAS as expressões forem verdadeiras') print('NOT - inverte o valor lógico de uma expressão (negação)\n') tem_cafe = True tem_pao = False #OR print(tem_cafe or tem_pao) print(tem_cafe or tem_cafe) print(tem_pao or tem_pao) #AND print(tem_cafe and tem_pao) print(tem_cafe and tem_cafe) #NOT print(not tem_cafe) print(not tem_pao) print('--' *30 ) print('OPERADORES RELACIONAIS:\n') #O Python possui 6 operadores relacionais print('Maior que: >') print('Maior ou Igual: >=') print('Menor que: <') print('Menor ou Igual: <=') print('Igual: ==') print('Diferente: != \n') comparador1 = 5 comparador2 = 3 print(comparador1 > comparador2) print(comparador1 >= comparador2) print(comparador1 < comparador2) print(comparador1 <= comparador2) print(comparador1 == comparador2) print(comparador1 != comparador2)
false
431e4b3687f6e41381331f315f13108fc029d396
wangyunge/algorithmpractice
/eet/Check_Completeness_of_a_Binary_Tree.py
1,354
4.21875
4
""" Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example 1: Input: root = [1,2,3,4,5,6] Output: true Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. Example 2: Input: root = [1,2,3,4,5,null,7] Output: false Explanation: The node with value 7 isn't as far left as possible. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isCompleteTree(self, root): """ :type root: TreeNode :rtype: bool """ self.max_val = 0 self.sum = 0 def _dfs(node, value): if node: self.max_val = max(self.max_val, value) self.sum += value _dfs(node.left, 2 * value) _dfs(node.right, 2 * value + 1) _dfs(root, 1) return self.sum == self.max_val/2 * (1+self.max_val)
true
597bdffceea740761f6280470d81b9deaf73f400
wangyunge/algorithmpractice
/int/517_Ugly_Number.py
926
4.125
4
''' Write a program to check whether a given number is an ugly number`. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. Notice Note that 1 is typically treated as an ugly number. Have you met this question in a real interview? Yes Example Given num = 8 return true Given num = 14 return false ''' class Solution: # @param {int} num an integer # @return {boolean} true if num is an ugly number or false def isUgly(self, num): if num < 1: return False while True: if num % 2 == 0: num = num/2 elif num % 3 == 0: num = num/3 elif num % 5 == 0: num = num/5 else: break if num != 1: return False else: return True
true
2e3a39178816c77f9f212cb1629a8f17950da152
wangyunge/algorithmpractice
/int/171_Anagrams.py
692
4.34375
4
''' Given an array of strings, return all groups of strings that are anagrams. Notice All inputs will be in lower-case Have you met this question in a real interview? Yes Example Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"]. Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"]. ''' class Solution: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): table = {} res = [] for word in strs: setOfWord = set(word) if setOfWord not in table: table[setOfWord] = word else: res.append(word) return res
true
e3ee7499abf955e0662927b7341e93fa81843620
wangyunge/algorithmpractice
/eet/Arithmetic_Slices.py
960
4.15625
4
""" An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [1,2,3,4] Output: 3 Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. Example 2: Input: nums = [1] Output: 0 """ class Solution(object): def numberOfArithmeticSlices(self, nums): """ :type nums: List[int] :rtype: int """ diff = [nums[i] - num[i-1] for i in range(1, len(nums))] consecutive = [0] * len(nums) for i in range(2, len(nums)): consecutive[i] = 2 * consecutive[i-1] - consecutive[i-2] + 1 for i in range(diff):
true
3859966faca648ffe0b7e83166049c07676ba93b
wangyunge/algorithmpractice
/eet/Maximum_Units_on_a_Truck.py
2,304
4.125
4
""" You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. numberOfUnitsPerBoxi is the number of units in each box of the type i. You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck. Example 1: Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 Output: 8 Explanation: There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. Example 2: Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 Output: 91 """ class Solution(object): def maximumUnits(self, boxTypes, truckSize): """ :type boxTypes: List[List[int]] :type truckSize: int :rtype: int """ if truckSize < 0: return 0 last_dp = [0 for _ in range(truckSize+1)] dp = [0 for _ in range(truckSize+1)] for i in range(len(boxTypes)): for j in range(1, truckSize+1): for num in range(1, boxTypes[i][0]+1): spare_track = j - num if spare_track >= 0: dp[j] = max(dp[j],last_dp[spare_track]+num*boxTypes[i][1]) last_dp = dp[:] return dp[-1] """ Notes: last dp and dp, need two states. """ class Solution(object): def maximumUnits(self, boxTypes, truckSize): """ :type boxTypes: List[List[int]] :type truckSize: int :rtype: int """ order_box = sorted(boxTypes, key=lambda x: x[1]) space = 0 res = 0 for box_num, box_unit in order_box: for num in range(1, box_num+1): if 1 + space <= truckSize: space += 1 res += box_unit return res
true
d620071842e6003015b2a9f34c72b85a64e00a04
wangyunge/algorithmpractice
/eet/Multiply_Strings.py
1,183
4.125
4
""" Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Constraints: 1 <= num1.length, num2.length <= 200 num1 and num2 consist of digits only. Both num1 and num2 do not contain any leading zero, except the number 0 itself. """ class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ l1 = len(num1) l2 = len(num2) res = [0] * (l1 + l2 +1) for i in range(l1)[::-1]: for j in range(l2)[::-1]: pdc = int(num1[i]) * int(num2[j]) plus = res[i+j] + pdc res[i+j] += pdc % 10 res[i+j+1] = pdc / 10 res = map(res, lambda x: str(x)) if res[0] == '0': return ''.join(res[1:]) else: return ''.join(res)
true
bdfc9caa3090f7727fd227548a83aaf19bf66c14
wangyunge/algorithmpractice
/eet/Unique_Binary_Search_Tree_II.py
1,269
4.25
4
''' Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 Subscribe to see which companies asked this question ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ def generateByList(self,list): root = TreeNode(list[0]) for i in xrange(1,len(list)): self.BSTappend(root,list[i]) return root def BSTappend(self,root,num): parent = root while root: parent = root if root.val < num: root = root.right else: root = root.left if parent.val < num: parent.right = TreeNode(num) else: parent.left = TreeNode(num)
true
9eba4c97143250a68995688a62b41145ab39485f
wangyunge/algorithmpractice
/int/165_Merge_Two_Sorted_Lists.py
944
4.125
4
''' Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order. Have you met this question in a real interview? Yes Example Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null. ''' z""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param two ListNodes @return a ListNode """ def mergeTwoLists(self, l1, l2): helper = ListNode(0,None) index = helper while l1 and l2: if l1.val <= l2.val: index.next = l1 l1 = l1.next else: index.next = l2 l2 = l2.next index = index.next index.next = l1 if l1 else l2 return helper.next
true
ba2b9d296a98edfb414c89aba262142b031014ea
tasver/python_course
/lab7_4.py
782
4.375
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- def input_str() -> str: """ This function make input of string data""" input_string = str(input('Enter your string: ')) return input_string def string_crypt(string: str) -> str: """ This function make crypt string""" result_string = str() string = string.lower() for symb in string: result_string += chr(ord(symb) + 1) return result_string def string_check_crypt(check_str:str) -> str: """ this funtion checking out of range crypt """ check_str = check_str.replace("{","a") check_str = check_str.replace("ѐ","а") print(check_str) return check_str def output_str(string:str) -> str: """ This function print result""" print(string) output_str(string_check_crypt(string_crypt(input_str())))
true
e18e81c8986c383ac6d6cec86017d3bf948af5b3
tasver/python_course
/lab6_1.py
719
4.21875
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- import math def input_par() -> list: """ This function make input of data""" a, b, c = map(float, input('Enter 3 numbers: ').split()) return [a, b, c] def check_triangle(a:list) -> bool: """ This function check exists triangle""" if (((a[0] + a[1]) > a[2]) and ((a[0] + a[2]) > a[1]) and ((a[2] + a[1] > a[0]))): return True else: return False def calculate(a:list) -> float: """ This function calculate area triangle """ if check_triangle(a): half_perimetr = (a[0]+a[1]+a[2])/2 area = math.sqrt(half_perimetr*(half_perimetr-a[0])*(half_perimetr-a[1])*(half_perimetr-a[2])) return area else: return 'Triangle not exists' print(calculate(input_par()))
true
3a5ee700dce71d3f72eb95a8d7b5900e309270ec
ahmetYilmaz88/Introduction-to-Computer-Science-with-Python
/ahmet_yilmaz_hw6_python4_5.py
731
4.125
4
## My name: Ahmet Yilmaz ##Course number and course section: IS 115 - 1001 - 1003 ##Date of completion: 2 hours ##The question is about converting the pseudocode given by instructor to the Python code. ##set the required values count=1 activity= "RESTING" flag="false" ##how many activities numact= int(input(" Enter the number of activities: ")) ##enter the activities as number as numact that the user enter while count < numact: flag= " true " activity= input( "Enter your activity: ") ##display the activity if activity=="RESTING": print ( " I enjoy RESTING too ") else: print ("You enjoy " , activity) count=count+1 if flag== "false": print (" There is no data to process ")
true
8d07696850cc5f7371069a98351c51266b77da6b
lintangsucirochmana03/bigdata
/minggu-02/praktik/src/DefiningFunction.py
913
4.3125
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b >>> print() >>> # Now call the function we just defined: >>> fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> fib <function fib at 0x02C4CE88> >>> f = fib >>> f(100) 0 1 1 2 3 5 8 13 21 34 55 89 >>> fib(0) >>> print(fib(0)) None >>> def fib2(n): # return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a+b return result >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>>
true
652990fdc99924c1810dddc60be12a8d81709a6e
ashwani8958/Python
/PyQT and SQLite/M3 - Basics of Programming in Python/program/module/friends.py
379
4.125
4
def food(f, num): """Takes total and no. of people as argument""" tip = 0.1*f #calculates tip f = f + tip #add tip to total return f/num #return the per person value def movie(m, num): """Take total and no. of the people as arguments""" return m/num #returns the per persons value print("The name attribute is: ", __name__)#check for the name attribute
true
95e0619eeb977cefe6214f8c50017397ec35af3b
SURBHI17/python_daily
/prog fund/src/assignment40.py
383
4.25
4
#PF-Assgn-40 def is_palindrome(word): word=word.upper() if len(word)<=1: return True else: if word[0]==word[-1]: return is_palindrome(word[1:-1]) else: return False result=is_palindrome("MadAMa") if(result): print("The given word is a Palindrome") else: print("The given word is not a Palindrome")
true
afdd7db2d0487b2cc2af9a6c33bcdc5c61512109
SURBHI17/python_daily
/prog fund/src/day4_class_assign.py
338
4.1875
4
def duplicate(value): dup="" for element in value: if element in dup: #if element not in value: continue # dup+=element else: # dup+=element #return dup return dup value1="popeye" print(duplicate(value1))
false
cdcab6d17e29620c08c0853e7b667c18e15ad1f5
mylessbennett/reinforcing_exercises_feb20
/exercise1.py
247
4.125
4
def sum_odd_num(numbers): sum_odd = 0 for num in numbers: if num % 2 != 0: sum_odd += num return sum_odd numbers = [] for num in range(1, 21): numbers.append(num) sum_odd = sum_odd_num(numbers) print(sum_odd)
false
114dd9807e3e7a111c6e1f97e331a7a98e6e074a
KanuckEO/Number-guessing-game-in-Python
/main.py
1,491
4.28125
4
#number_guessing_game #Kanuck Shah #importing libraries import random from time import sleep #asking the highest and lowest index they can guess low = int(input("Enter lowest number to guess - ")) high = int(input("Enter highest number to guess - ")) #array first = ["first", "second", "third", "fourth", "fifth"] #variables second = 0 #tries counter tries = 1 #array for highest and lowest index that they can guess numbers = [low, high] #choosing random number between array above number = random.randint(low, high) #printting for style print("\n") print("************************************") print("Welcome to the number guessing game.") print("************************************") print("\n") print("You will have to choose a number between", low ,"and", high ,"in eight tries") #delay sleep(1) print(".") sleep(1) print(".") sleep(1) print(".") sleep(1) print("\n") while tries < 8: tries += 1 print("choose your", first[second] ,"number ", end="") ans1 = int(input("")) second += 1 print("You have tried to guess", tries, "times.") if int(number) > ans1: print("\n") print("Too low go higher") elif int(number) < ans1: print("\n") print("Too high go lower") elif int(number) == ans1: print("\n") print("Ding Ding Ding") print("You are right") print("The number was", number) break if tries >= 8: print("\n") print("The number was", number) print("Too many tries session ended") print("Better luck next time :(")
true
9bab6ff99aa72e668524b63523c2106181049f6f
IamBiasky/pythonProject1
/SelfPractice/function_exponent.py
316
4.34375
4
# Write a function called exponent(base, exp) # that returns an int value of base raises to the power of exp def exponent(base, exp): exp_int = base ** exp return exp_int base = int(input("Please enter a base integer: ")) exp = int(input("Please enter an exponent integer: ")) print(exponent(base, exp))
true
2d4cf0b46c47fad8a5cc20cdf98ebf9ab379a151
sooryaprakash31/ProgrammingBasics
/OOPS/Exception_Handling/exception_handling.py
1,347
4.125
4
''' Exception Handling: - This helps to avoid the program crash due to a segment of code in the program - Exception handling allows to manage the segments of program which may lead to errors in runtime and avoiding the program crash by handling the errors in runtime. try - represents a block of code that can throw an exception. except - represents a block of code that is executed when a particular exception is thrown. else - represents a block of code that is executed when there is no exception finally - represents a block of code that is always executed irrespective of exceptions raise - The raise statement allows the programmer to force a specific exception to occur. ''' dividend = float(input("Enter dividend ")) divisor = float(input("Enter divisor ")) #runs the code segment which may lead to error try: result = dividend/divisor #executed when there is an exception except ZeroDivisionError: print("Divisor is Zero") #executed when there is no exception else: print(format(result,'.2f')) #always executed finally: print("End of Program") ''' try: if divisor == 0: raise ZeroDivisionError() except ZeroDivisionError: print("Divisor is zero") else: result = dividend/divisor print(format(result, '.2f')) finally: print("End of Program") '''
true
79dda99fe42354f17d03eb33a1aab1ee9ebe61ab
sooryaprakash31/ProgrammingBasics
/Algorithms/Sorting/Quick/quick.py
2,027
4.25
4
''' Quick Sort: - Picks a pivot element (can be the first/last/random element) from the array and places it in the sorted position such that the elements before the pivot are lesser and elements after pivot are greater. - Repeats this until all the elements are placed in the right position - Divide and conquer strategy Example: arr=[3,6,4,5,9] Takes pivot as arr[2] (i.e (first_index+last_index)/2) pivot is 4. After 1st partition arr=[3,4,6,5,9] i) The elements before pivot are lesser then pivot and the elements after pivot are greater than pivot - quick_sort method calls itself for left and right blocks having partition as the midpoint until all the elements are sorted. ''' def partition(arr, left,right,pivot): #left should always less than or equal to right #otherwise it will lead to out of bounds error while left<=right: #finds the first element that is greater than pivot #from the start while arr[left]<pivot: left=left+1 #finds the first element that is lesser than pivot #from the end while arr[right]>pivot: right=right-1 #swapping the elements at indices left and right if left<=right: arr[left],arr[right]=arr[right],arr[left] left=left+1 right=right-1 #returning the current index of the pivot element return left def quick_sort(arr,left,right): #checks if the block contains atleast two elements if left<right: #Middle element is chosen as the pivot pivot=arr[(left+right)//2] #gives the sorted pivot index p = partition(arr,left,right,pivot) #calls quick_sort for elements left to the partition quick_sort(arr,left,p-1) #calls quick_sort for elements right to the partition quick_sort(arr,p,right) arr=list(map(int,input("Enter array ").split())) print("Before sort:",*arr) #calling sort function quick_sort(arr,0,len(arr)-1) print("Sorted array:",*arr)
true
4bdde3d9684f505ae85c0446465aa211a012a02d
luizfirmino/python-labs
/Python I/Assigments/Module 5/Ex-2.py
415
4.3125
4
# # Luiz Filho # 3/14/2021 # Module 5 Assignment # 2. In mathematics, the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅ n (as the product of all integer numbers from 1 to n). # For example, 4! = 1 ⋅ 2 ⋅ 3 ⋅ 4 = 24. Write a recursive function for calculating n! def calculateN(num): if num == 1: return num else: return num * calculateN(num-1) print(calculateN(4))
true
7372b7c995d2302f29b8443656b50cae298a566b
luizfirmino/python-labs
/Python I/Assigments/Module 6/Ex-4.py
742
4.40625
4
# # Luiz Filho # 3/23/2021 # Module 6 Assignment # 4. Write a Python function to create the HTML string with tags around the word(s). Sample function and result are shown below: # #add_html_tags('h1', 'My First Page') #<h1>My First Page</h1> # #add_html_tags('p', 'This is my first page.') #<p>This is my first page.</p> # #add_html_tags('h2', 'A secondary header.') #<h2>A secondary header.</h2> # #add_html_tags('p', 'Some more text.') #<p>Some more text.</p> def add_html_tags(tag, value): return "<" + tag + ">" + value + "</" + tag + ">" print(add_html_tags('h1', 'My First Page')) print(add_html_tags('p', 'This is my first page.')) print(add_html_tags('h2', 'A secondary header.')) print(add_html_tags('p', 'Some more text.'))
true
c13619368c38c41c0dbf8649a3ca88d7f2788ee8
luizfirmino/python-labs
/Python Networking/Assignment 2/Assignment2.py
564
4.21875
4
#!/usr/bin/env python3 # Assignment: 2 - Lists # Author: Luiz Firmino list = [1,2,4,'p','Hello'] #create a list print(list) #print a list list.append(999) #add to end of list print(list) print(list[-1]) #print the last element list.pop() #remove last element print(list) print(list[0]) #print first element list.remove(1) #remove element print(list) del list[3] #remove an element by index print(list) list.insert(0,'Baby') #insert an element at index print(list)
true
51d1e3a48b954c1de3362ea295d4270a884fea98
luizfirmino/python-labs
/Python I/Assigments/Module 7/Ex-3.py
1,042
4.3125
4
# # Luiz Filho # 4/7/2021 # Module 7 Assignment # 3. Gases consist of atoms or molecules that move at different speeds in random directions. # The root mean square velocity (RMS velocity) is a way to find a single velocity value for the particles. # The average velocity of gas particles is found using the root mean square velocity formula: # # μrms = (3RT/M)½ root mean square velocity in m/sec # # R = ideal gas constant = 8.3145 (kg·m2/sec2)/K·mol # # T = absolute temperature in Kelvin # # M = mass of a mole of the gas in kilograms. molar mass of O2 = 3.2 x 10-2 kg/mol # # T = °C + 273 # # a. By using the decimal module, create a decimal object and apply the sqrt and quantize method (match pattern “1.000”) # and provide the answer to the question: # What is the average velocity or root mean square velocity of a molecule in a sample of oxygen at 25 degrees Celsius? number = 3237945.76 print("{:25,.9f}".format(number)) print("{:.2f}".format(number)) print("{:,.2f}".format(number)) print("{:,.4f}".format(number))
true
47d783748c562dd3c3f8b7644dda166f37b5f11e
luizfirmino/python-labs
/Python I/Assigments/Module 5/Ex-6.py
238
4.5
4
# # Luiz Filho # 3/14/2021 # Module 5 Assignment # 6. Write a simple function (area_circle) that returns the area of a circle of a given radius. # def area_circle(radius): return 3.1415926535898 * radius * radius print(area_circle(40))
true
6ca6fbf8e7578b72164ab17030f1c01013604b04
luizfirmino/python-labs
/Python I/Assigments/Module 5/Ex-4.py
549
4.28125
4
# # Luiz Filho # 3/14/2021 # Module 5 Assignment # 4. Explain what happens when the following recursive functions is called with the value “alucard” and 0 as arguments: # print("This recursive function is invalid, the function won't execute due an extra ')' character at line 12 column 29") print("Regardless any value on its parameters this function will not execute or compile.") def semordnilap(aString,index): if index < len(aString): print(aString[index]), end="") semordnilap(aString, index+1) semordnilap("alucard", 0)
true
796c8bb615635d769a16ae12d9f27f2cfce4631c
luizfirmino/python-labs
/Python I/Assigments/Module 2/Ex-2.py
880
4.53125
5
# # Luiz Filho # 2/16/2021 # Module 2 Assignment # Assume that we execute the following assignment statements # # length = 10.0 , width = 7 # # For each of the following expressions, write the value of the expression and the type (of the value of the expression). # # width//2 # length/2.0 # length/2 # 1 + 4 * 5 # length = 10.0 width = 7 print("-- DEFAULTS --------------") print("Variable width value = " + str(width)) print("Variable length value = " + str(length)) print("--------------------------") print("Result of width//2: " + str(width//2) + " output type:" + str(type(width//2))) print("Result of length/2.0: " + str(length/2.0) + " output type:" + str(type(length/2.0))) print("Result of length/2: " + str(length/2) + " output type:" + str(type(length/2))) print("Result of 1 + 4 * 5: " + str((1 + 4 * 5)) + " output type:" + str(type((1 + 4 * 5))))
true
2dcdbed4df8b0608780c4d3a226c4f25d0de2b38
Zetinator/just_code
/python/leetcode/binary_distance.py
872
4.1875
4
""" The distance between 2 binary strings is the sum of their lengths after removing the common prefix. For example: the common prefix of 1011000 and 1011110 is 1011 so the distance is len("000") + len("110") = 3 + 3 = 6. Given a list of binary strings, pick a pair that gives you maximum distance among all possible pair and return that distance. """ def binary_distance(x: 'binary string', y: 'binary string') -> 'distance': def find_prefix(x, y, n): if not x or not y: return n # print(f'STATUS: x:{x}, y:{y}, n:{n}') if x[0] == y[0]: return find_prefix(x[1:], y[1:], n+1) else: return n prefix_len = find_prefix(x, y, 0) x, y = x[prefix_len:], y[prefix_len:] return len(x) + len(y) # test x = '1011000' y = '1011110' print(f'testing with: x:{x}, y:{y}') print(f'ANS: {binary_distance(x, y)}')
true
308f485babf73eec8c433821951390b8c2414750
Zetinator/just_code
/python/leetcode/pairs.py
966
4.1875
4
"""https://www.hackerrank.com/challenges/pairs/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=search You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value. Complete the pairs function below. It must return an integer representing the number of element pairs having the required difference. pairs has the following parameter(s): k: an integer, the target difference arr: an array of integers. """ from collections import Counter def pairs(k, arr): counter = Counter() n_pairs = 0 for e in arr: # print(f'e: {e}, counter: {counter}, n_pairs: {n_pairs}') if e in counter: n_pairs += counter[e] counter[e+k] += 1 counter[e-k] += 1 return n_pairs # test k = 2 arr = [1,3,5,8,6,4,2] print(f'testing with: {arr}') print(f'ans: {pairs(k, arr)}')
true
e823b273ed44482d8c05499f66bf76e78b06d842
Zetinator/just_code
/python/leetcode/special_string_again.py
2,477
4.21875
4
"""https://www.hackerrank.com/challenges/special-palindrome-again/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=strings A string is said to be a special string if either of two conditions is met: All of the characters are the same, e.g. aaa. All characters except the middle one are the same, e.g. aadaa. A special substring is any substring of a string which meets one of those criteria. Given a string, determine how many special substrings can be formed from it. """ def is_special(s): """checks if the substring is "special" """ # special case: if len(s) == 1: return True # general case match = s[0] for i in range(len(s)//2): if s[i] != match or s[i] != s[-(1+i)]: return False return True def substrCount(n, s): """counts how many substrings are "special" somehow not fast enought... maybe because of the function call """ n_specials = 0 for i in range(len(s)): for j in range(i, len(s)): n_specials += 1 if is_special(s[i:j+1]) else 0 return n_specials def substrCount(n, s): res = 0 count_sequence = 0 prev = '' for i,v in enumerate(s): # first increase counter for all seperate characters count_sequence += 1 if i and (prev != v): # if this is not the first char in the string # and it is not same as previous char, # we should check for sequence x.x, xx.xx, xxx.xxx etc # and we know it cant be longer on the right side than # the sequence we already found on the left side. j = 1 while ((i-j) >= 0) and ((i+j) < len(s)) and j <= count_sequence: # make sure the chars to the right and left are equal # to the char in the previous found squence if s[i-j] == prev == s[i+j]: # if so increase total score and step one step further out res += 1 j += 1 else: # no need to loop any further if this loop did # not find an x.x pattern break #if the current char is different from previous, reset counter to 1 count_sequence = 1 res += count_sequence prev = v return res # test # s = 'asasd' s = 'abcbaba' n = 5 print(f'testing with: {s}') print(f'ans: {substrCount(n, s)}')
true
e2b8fe6ba7d4d000b5ef8578aae3caf1847efc9d
Zetinator/just_code
/python/leetcode/unique_email.py
1,391
4.375
4
""" Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s. If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.) If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.) It is possible to use both of these rules at the same time. Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails? """ def unique_email(x: 'array with emails')-> 'array with unique emails': ans = set() for e in x: name, domain = e.split('@') name = e.replace('.','').split('+')[0] ans.add(f'{name}@{domain}') return list(ans) # test test = ["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com"] print(f'testing with: {test}') print(f'ANS: {unique_email(test)}')
true
ca54ebba62347e2c3a4107872889e4746c51a922
malbt/PythonFundamentals.Exercises.Part5
/anagram.py
497
4.375
4
def is_anagram(first_string: str, second_string: str) -> bool: """ Given two strings, this functions determines if they are an anagram of one another. """ pass # remove pass statement and implement me first_string = sorted(first_string) second_string = sorted(second_string) if first_string == second_string: print("anagram") else: print("not anagram") first_string = "dormitory" second_string = "dirtyroom" is_anagram(first_string, second_string)
true
e777115b8048caa29617b9b0e99d6fbac3beef99
Vipulhere/Python-practice-Code
/Module 8/11.1 inheritance.py
643
4.3125
4
#parent class class parent: parentname="" childname="" def show_parent(self): print(self.parentname) #this is child class which is inherites from parent class Child(parent): def show_child(self): print(self.childname) #this object of child class c=Child() c.parentname="BOB" c.childname="David" c.show_parent() c.show_child() print("___________________") class car: def __init__(self,name="ford",model=2015): self.name=name self.model=model def sport(self): print("this is sport car") class sportcar(car): pass c=sportcar("sportcar") print(c.name) print(c.model) c.sport()
true
4380cb3cb4bbdace75f27ff7059a0505e17687b7
ToxaRyd/WebCase-Python-course-
/7.py
1,757
4.3125
4
""" Данный класс создан для хранения персональной (смею предположить, корпоративной) информации. Ниже приведены doc тесты/примеры работы с классом. >>> Employee = Person('James', 'Holt', '19.09.1989', 'surgeon', '3', '5000', 'Germany', 'Berlin', 'male') >>> Employee.name James Holt >>> Employee.age 29 years old >>> Employee.work He is a surgeon >>> Employee.money 180 000 >>> Employee.home Lives in Berlin, Germany """ class Person: def __init__(self, first_name, last_name, birth_date, job, working_years, salary, country, city, gender='uknown'): self.__first_name = first_name self.__last_name = last_name self.__birth_date = birth_date self.__job = job self.__working_years = working_years self.__salary = salary self.__country = country self.__city = city self.__gender = gender @property def name(self): print(f'{self.__first_name} {self.__last_name}') @property def age(self): a = list(self.__birth_date.split('.')) b = 2018 - int(a[2]) print(f'{b} years old') @property def work(self): ci = {'male': 'He', 'female': 'She', 'uknown': 'He/She'} print('{0} is a {1}'.format(ci[self.__gender], self.__job)) @property def money(self): m = int(self.__working_years) * int(self.__salary) * 12 print('{0:,}'.format(m).replace(',', ' ')) @property def home(self): print(f'Lives in {self.__city}, {self.__country}') if __name__ == '__main__': import doctest doctest.testmod()
false
347460f3edf3af4e5601a45b287d1a086e1a3bc3
bopopescu/PycharmProjects
/Class_topic/7) single_inheritance_ex2.py
1,601
4.53125
5
# Using Super in Child class we can alter Parent class attributes like Pincode # super is like update version of parent class in child class '''class UserProfile(Profile): # Child Class def __init__(self,name,email,address,pincode): # constructor of child Class super(UserProfile, self).__init__(name,email,address) # parent containing three attributes self.pincode = pincode''' class Profile: # Parent Class def __init__(self, name, email, address): # constructor of parent class self.name = name self.email = email self.address = address def displayProfile(self): # display method in parent class return "Name:{0}\nEmail:{1}\nAddress:{2}".format( self.name, self.email, self.address ) class UserProfile(Profile): # Child Class def __init__(self,name,email,address,pincode): # constructor of child class super(UserProfile, self).__init__(name,email,address) # parent containing three attributes self.pincode = pincode def setCity(self, city): # setCity method of child lass self.city = city def displayProfile(self): # display method in child class return "Name:{0}\nEmail:{1}\nAddress:{2}\nCity:{3}\nPincode:{4}".format( self.name, self.email, self.address, self.city, self.pincode ) user = UserProfile("Raju","raju@gmail.com","BTM","580045") # object of child class user.setCity("Bangalore") # adding attribute value to child class temp = user.displayProfile() print(temp)
true
6a6b1394a960ba09ff2c97fa71e61b78a1c45858
bopopescu/PycharmProjects
/shashi/10) functions_1( lambda) .py
1,902
4.25
4
#Nested function '''def func1(): def func2(): return "hello" return func2 data = func1() print(data())''' #global function '''a = 100 def test(): global a # ti use a value in function a = a + 1 print(a) #print(a) test()''' '''a = 100 def test(): global a # ti use a value in function b = 100 a = a + 1 print(a) #print(a) test() print(b)''' # doc string / documentation function '''def add(a,b): # """ enter then the it will execute :param a: # :par b: # :return:am """ :param a: :par b: :return:am """ return a + b print(add.__doc__) add(1,2)''' # default parameter intialization '''def add(a,b = 100): return a + b temp = add(1) print(temp)''' # closure function '''def func1(a): def func2(b): return "iam function2" def func3(c): return "i am from func3" return [func2,func3] data = func1(11) #print(data[0]) #print(data[1]) print(data[0](11)) print(data[1](11))''' '''def test(a,b): if a > b: return" ai s largest" else: return "b is largest" large = test(10,20) print(large) print("============")''' #lamda - terinary expression : True if condition False #lambda p1,p2,pn:expression #exp ? value1 : value2 # to find largest to two no's using lambda function '''data = lambda a,b: 'a is largest' if a > b else "b is largest" #print(data) #print(data()) # error statement print(data(200,300))''' # to find largest to three no's using lambda function '''data = lambda a,b,c: a if a > b and a > c else b if b > c else c #print(data) #print(data()) # error statement print(data(2000,3000,500))''' # to find largest to four no's using lambda function data = lambda a,b,c,d: a if a > b and a > c and a > d else b if b > c and b > d else c if c > d else d #print(data) #print(data()) # error statement print(data(200,700,9000,6))
false
1f6a9e033c3a3b8c5c278cb4a96d5900ef8a994e
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/roadtrip/roadtrip-v1.py
1,130
4.15625
4
city_dict = { 'Boston': {'New York', 'Albany', 'Portland'}, 'New York': {'Boston', 'Albany', 'Philadelphia'}, 'Albany': {'Boston', 'New York', 'Portland'}, 'Portland': {'Boston', 'Albany'}, 'Philadelphia': {'New York'} } city_dict2 = { 'Boston': {'New York': 4, 'Albany': 6, 'Portland': 3}, 'New York': {'Boston': 4, 'Albany': 5, 'Philadelphia': 9}, 'Albany': {'Boston': 6, 'New York': 5, 'Portland': 7}, 'Portland': {'Boston': 3, 'Albany': 7}, 'Philadelphia': {'New York': 9}, } class Trip(): def __init__(self, starting_city, hops=1, city_dict=city_dict, city_dict2=city_dict2): self.starting_city = starting_city self.hops = hops self.city_dict = city_dict self.city_dict2 = city_dict2 def show_cities(self): one_hop_set = self.city_dict[self.starting_city] one_hop_list = [city for city in one_hop_set] two_hops = [self.city_dict[city] for city in one_hop_list] print(f"one hop: {one_hop_set}") print(f"two hops: {two_hops}") start_city = input("Starting city: ") this_trip = Trip(start_city) this_trip.show_cities()
false
7c693a0fe73b2fe3cbeeddf1551bf3d2f0250ab2
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab12/lab12-guess_the_number-v3.py
694
4.34375
4
''' lab12-guess_the_number-v3.py Guess a random number between 1 and 10. V3 Tell the user whether their guess is above ('too high!') or below ('too low!') the target value.''' import random x = random.randint(1, 10) guess = int(input("Welcome to Guess the Number v3. The computer is thinking of a number between 1 and 10.\nEnter your guess: ")) count = 0 while True: count = count + 1 if guess == x: print(f"Congrats. You guessed the computer's number and it only took you {count} times!") break else: if guess > x: guess = int(input("Too high... Try again: ")) if guess < x: guess = int(input("Too low... Try again: "))
true
82ef1519965203526bf480fc9b989e73fb955f54
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab17-palidrome_anagramv2.py
312
4.5625
5
# Python Program to Check a Given String is Palindrome or Not string = input("Please enter enter a word : ") str1 = "" for i in string: str1 = i + str1 print("Your word backwards is : ", str1) if(string == str1): print("This is a Palindrome String") else: print("This is Not a Palindrome String")
true
81ff46e99809f962f6642b33aa03dd274ac7a16e
mohasinac/Learn-LeetCode-Interview
/Strings/Implement strStr().py
963
4.28125
4
""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). """ class Solution: def strStr(self, haystack: str, needle: str) -> int: n = len(needle) h = len(haystack) if n<1 or needle==haystack: return 0 if h<1: return -1 for i, c in enumerate(haystack): if c==needle[0] and (i+n)<=h and all([haystack[i+j]==needle[j] for j in range(1,n)]): return i return -1
true
997f0d32c5609f5e9dac7fb94b933f4e28d64809
jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO
/exercicio11.py
410
4.15625
4
# 11. Altere o programa anterior para mostrar no final a soma dos números. # Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01 num1 = int(input("Digite o primeiro número inteiro: ")) num2 = int(input("Digite o segundo número inteiro: ")) for i in range (num1 + 1, num2): print(i) for i in range (num2 + 1, num1): print(i) soma = num1 + num2 print("A soma dos dois números inteiros é: ", i + i)
false
16cbb114d0a13ac1c2a25c4be46dd7c14db6584c
Divyendra-pro/Calculator
/Calculator.py
761
4.25
4
#Calculator program in python #User input for the first number num1 = float(input("Enter the first number: ")) #User input for the operator op=input("Choose operator: ") #User input for the second number num2 = float(input("Enter the second number:" )) #Difine the operator (How t will it show the results) if op == '+': print("You choosed for Addition ") print(num1+num2) elif op == '-': print("You choosed for subtraction ") print(num1-num2) elif op == '*': print("You choosed for multiplication ") print(num1*num2) elif op == '/': print("Your choosed for division ") print(num1/num2) else: print("Enter a valid operator") print("Some valid operators: " "+ " "- " "* " "/ ")
true
8a3f462060774d17383f404bf97467015cd94489
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex053_detector_de_palindromo.py
1,157
4.15625
4
# Class Challenge 13 # Ler uma frase e verificar se é um Palindromo # Palindromo: Frase que quando lida de frente para traz e de traz para frente # Serão a mesma coisa # Ex.: Apos a sopa; a sacada da casa; a torre da derrota; o lobo ama o bolo; # Anotaram a data da maratona. # Desconsiderar os espaços e acentos. Programa tira os espaços print('Descobrindo se a frase é um Palindromo.') frase = str(input('Digite uma frase: ')).strip().upper() array = frase.split() junto = ''.join(array) n = len(junto) s = 0 for a in range(1, n+1): if junto[a-1] != junto[n-a]: s += 1 if s == 0: print('A frase é um Palindromo.') else: print('A frase não é um Palindromo') # Exemplo do professor print('\nExemplo do professor: ') palavras = frase.split() inverso = '' for letra in range(len(junto)-1, -1, -1): inverso += junto[letra] print('O inverso de {} é {}.'.format(junto, inverso)) if inverso == junto: print('Temos um Palindromo') else: print('Não temos um Palindromo') # 3ª Alternativa como o Python inverso2 = junto[::-1] # Frase junto, do começo ao fim, porém de traz para frente # Por isso o -1 print(inverso2)
false
4d7ae2dfa428ee674fdd151230a36c39c09e7055
NathanaelV/CeV-Python
/Aulas Mundo 3/aula19_dicionarios.py
2,623
4.21875
4
# Challenge 90 - 95 # dados = dict() # dados = {'nome':'Pedro', 'idade':25} nome é o identificador e Pedro é o valor # idade é o identificador e 25 é a idade. # Para criar um novo elemento # dados['sexo'] = 'M'. Ele cria o elemento sexo e adiciona ao dicionario # Para apagar # del dados['idade'] # print(dados.values()) Ele retornará - 'Pedro', 25, 'M' # print(dados.keys()) It will return - 'nome', 'idade', 'sexo' # print(dados.items()) it will return all things - 'name', 'Pedro' ... # Esses conceitos são bons para laços, for, while filme = {'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'} for k, v in filme.items(): print(f'O {k} é {v}') print() person = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 40} print(f'{person["nome"]} is {person["idade"]} years old.') # Não posso usar person[0] ele não reconhece print(f'Using person.keys(): {person.keys()}') print(f'Using person.values(): {person.values()}') print(f'Using person.items(): {person.items()}') # Using for: print('\nUsing for:') print('\nUsing For k in person.key: or For k in person:') for k in person.keys(): # = to use person print(k) print('\nUsing k in person.values():') for k in person.values(): print(k) print('\nUsing k, v in person.items():') for k, v in person.items(): print(f'V = {v}; K = {k}') del person['sexo'] print("\nAfter using del person['sexo']") for k, v in person.items(): print(f'V = {v}; K = {k}') # Alterando e adicionando elementos: print('\nChanging the name and adding weight.') person['peso'] = 98.5 person['nome'] = 'Leandro' for k, v in person.items(): print(f'V = {v}; K = {k}') # Criando um dicionário dentro de uma lista: Brazil = list() estado1 = {'UF': 'Rio Janeiro', 'sigla': 'RJ'} estado2 = {'UF': 'São Paulo', 'sigla': 'SP'} Brazil.append(estado1) Brazil.append(estado2) print(f'Brazil: {Brazil}') print(f'Estado 2: {estado2}') print(f'Brazil[0]: {Brazil[0]}') print(f"Brazil[0]['uf']: {Brazil[0]['UF']}") print(f"Brazil[1]['sigla']: {Brazil[1]['sigla']}") # Introsuzindo Valores: print('\nIntroduzindo Valores: ') brasil = list() estado = dict() for a in range(0, 3): estado['uf'] = str(input('UF: ')) estado['sigla'] = str(input('Sigla: ')) brasil.append(estado.copy()) # Caso use o [:] dará erro. for e in brasil: print(e['sigla'], ' = ', e['uf']) # Mostra os identificadores e os valores print('\nItems: ') for e in brasil: for k, v in e.items(): print(f'O compo {k} tem o valor {v}') # Mostra os valore dentro da lista print('\nValues:') for e in brasil: for v in e.values(): print(v, end=' - ') print()
false
8e28da8e0eb769a6a9735bb6edf36567011b2a0a
NathanaelV/CeV-Python
/Aulas Mundo 3/aula20_funçoes_parte1.py
1,450
4.1875
4
# Challenge 96 - 100 # Bom para ser usado quando um comando é muito repetido. def lin(): print('-' * 30) def título(msg): # No lugar de msg, posso colocar qualquer coia. print('-' * 30) print(msg) print('-' * 30) print(len(msg)) título('Im Learning Python') print('Good Bye') lin() def soma(a, b): print(F'A = {a} e B = {b}') s = a + b print(f'A soma A + B = {s}') print('\nSomando dois Valores') soma(4, 6) soma(b=5, a=8) # Posso inverter a ordem, contanto que deixe explicito quem é quem # Emapacotamento def cont(*num): # Vai pegar os parametros e desempacotar, não importq quantos print(num) # Vai mostrar uma tupla, entre parenteses. # Posso fazer tudo que faria com uma tupla def contfor(*num): for v in num: print(f'{v}', end=', ') print('Fim') def contar(*num): tam = len(num) print(f'Recebi os valores {num} e ao todo são {tam} números') print('\nContando o número de itens') contfor(1, 2, 3, 5, 3, 2) cont(1, 7, 3) contar(3) def dobra(lst): # Por ser uma lista, não preciso usar o * pos = 0 while pos < len(lst): lst[pos] *= 2 pos += 1 print('\nDobrando valores') value = [5, 3, 6, 3, 8, 9, 0] print(value) dobra(value) print(value) def somamelhor(*num): s = 0 for n in num: s += n print(f'A soma de {num} é igual a {s}.') print('\nSoma varios valores') somamelhor(3, 5, 1, 3) somamelhor(3, 5)
false
560596b12e9cda1ebdadfb4ab2b5c945ad0265d1
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex103_ficha_do_jogador.py
1,173
4.21875
4
# Class Challenge 21 # Montar a função ficha(): # Que recebe parametros opcionais: NOME de um jogador e quantos GOLS # O programa deve mostrar os dados, mesmo que um dos valores não tenha sido informado corretamente # jogador <desconhecido> fez 0 gols # Adicionar as docstrings da função def ficha(name='<unknown>', goals=0): """ -> Function to read a player name and scored :param name: (Optional) If user don't enter a name, the program will print '<unknown>' :param goals: (Optional) If user don't enter number of goals, the program will print 0 :return: No return """ print(f'Player {name} scored {goals} goals.') n = input('Whats player name: ') g = input('How many goals player scored: ') if n == '' and g == '': ficha() elif n == '': ficha(goals=g) elif g == '': ficha(n) else: ficha(n, g) # Teacher example: def fichap(nome='<desconhecido>', gol=0): print(f'O jogador {nome} fez {gol} gol(s).') # Principal Program n = str(input('Nome do Jogador: ')) g = str(input('Número de gol(s): ')) if g.isnumeric(): g = int(g) else: g = 0 if n.strip() == '': ficha(goals=g) else: ficha(n, g)
false
5d86ca4b127b79be2a7edc2a93e45dfc0502ccd7
JiJibrto/lab_rab_12
/individual2.py
1,358
4.34375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # Реализовать класс-оболочку Number для числового типа float. Реализовать методы # сложения и деления. Создать производный класс Real, в котором реализовать метод # возведения в произвольную степень, и метод для вычисления логарифма числа. import math class Number: def __init__(self, num): self.a = float(num) def sum(self, b): return self.a + b def deg(self, b): return self.a / b class Real (Number): def expo(self, b): return self.a ** b def log(self, b): return math.log(self.a, b) if __name__ == '__main__': print("Инициализация обьекта класса Number") a = Number(input("Enter a> ")) print(f"Сумма чисел: {a.sum(float(input('Enter b> ')))}") print(f"Деление чисел: {a.deg(float(input('Enter b> ')))}") print("Инициализация обьекта класса Real") b = Real(input("Enter a> ")) print(f"Нахождение логарифма: {b.log(int(input('Enter b> ')))}") print(f"Возведение в степень: {b.expo(int(input('Enter b> ')))}")
false
c80bffe95bc94308989cec03948a4a91239d13aa
rbngtm1/Python
/data_structure_algorithm/array/remove_duplicate_string.py
398
4.25
4
# Remove duplicates from a string # For example: Input: string = 'banana' # Output: 'ban' ########################## given_string = 'banana apple' my_list = list() for letters in given_string: if letters not in my_list: my_list.append(letters) print(my_list) print (''.join(my_list)) ## possile solution exist using set data structure but ## set structure is disorder
true
bed107a24a36afeb2176c3200aec2c525a24a55a
Silicon-beep/UNT_coursework
/info_4501/home_assignments/fraction_class/main.py
1,432
4.21875
4
from fractions import * print() ####################### print('--- setup -----------------') try: print(f'attempting fraction 17/0 ...') Fraction(17, 0) except: print() pass f1, f2 = Fraction(1, 2), Fraction(6, 1) print(f'fraction 1 : f1 = {f1}') print(f'fraction 2 : f2 = {f2}') ###################### print('--- math -------------------') # addition print(f'{f1} + {f2} = {f1 + f2}') # subtraction print(f'{f1} - {f2} = {f1 - f2}') # multiplication print(f'{f1} * {f2} = {f1 * f2}') # division print(f'{f1} / {f2} = {f1 / f2}') # floor division print(f'{f2} // {f1} = {f2 // f1}') # modulo print(f'{Fraction(7,1)} % {Fraction(2,1)} = {Fraction(7,1) % Fraction(2,1)}') # exponentiation # only works with a whole number as fraction 2 print(f'{f1} ** {f2} = {f1 ** f2}') # print(f'{Fraction(2,1)} ** {Fraction(5,4)} = {Fraction(2,1) ** Fraction(5,4)}') # print(2**(5/4), (Fraction(2, 1) ** Fraction(5, 4)).float) ##################### print('--- simplifying ------------') print(f'{f1} = {f1.simplify()}') print(f'{f2} = {f2.simplify()}') print(f'18/602 = {Fraction(18,602).simplify()}') print(f'72/144 = {Fraction(72,144).simplify()}') print(f'0/13 = {Fraction(0,10).simplify()}') #################### print('--- other things -----------') print(f'convert to float ... {f1} = {f1.float}, {f2} = {f2.float}') print(f'inverting a fraction ... {f1} inverts to {f1.invert()}') #################### print()
false
3474489ac3abf4439f4af04a6f2a69a743e168d6
divanescu/python_stuff
/coursera/PR4E/assn46.py
348
4.15625
4
input = raw_input("Enter Hours: ") hours = float(input) input = raw_input("Enter Rate: ") rate = float(input) def computepay(): extra_hours = hours - 40 extra_rate = rate * 1.5 pay = (40 * rate) + (extra_hours * extra_rate) return pay if hours <= 40: pay = hours * rate print pay elif hours > 40: print computepay()
false
a6dd4e5cf972068af342c8e08e10b4c7355188e6
DivyaRavichandr/infytq-FP
/strong .py
562
4.21875
4
def factorial(number): i=1 f=1 while(i<=number and number!=0): f=f*i i=i+1 return f def find_strong_numbers(num_list): list1=[] for num in num_list: sum1=0 temp=num while(num): number=num%10 f=factorial(number) sum1=sum1+f num=num//10 if(sum1==temp and temp!=0): list1.append(temp) return list1 num_list=[145,375,100,2,10] strong_num_list=find_strong_numbers(num_list) print(strong_num_list)
true
4f32d0b2293ff8535a870cd9730528ecf4874190
comedxd/Artificial_Intelligence
/2_DoublyLinkedList.py
1,266
4.21875
4
class LinkedListNode: def __init__(self,value,prevnode=None,nextnode=None): self.prevnode=prevnode self.value=value self.nextnode=nextnode def TraverseListForward(self): current_node = self while True: print(current_node.value, "-", end=" ") if (current_node.nextnode is None): print("None") break current_node = current_node.nextnode def TraverseListBackward(self): current_node = self while True: print(current_node.value, "-", end=" ") if (current_node.prevnode is None): print("None") break current_node = current_node.prevnode # driver code if __name__=="__main__": node1=LinkedListNode("Hello ") node2=LinkedListNode("Dear ") node3=LinkedListNode(" AI ") node4=LinkedListNode("Student") head=node1 tail=node4 # forward linking node1.nextnode=node2 node2.nextnode=node3 node3.nextnode=node4 # backward linking node4.prevnode=node3 node3.prevnode=node2 node2.prevnode=node1 head.TraverseListForward() tail.TraverseListBackward()
true
76348acf643b1cd9764e1184949478b3b888b014
jdipendra/asssignments
/multiplication table 1-.py
491
4.15625
4
import sys looping ='y' while(looping =='y' or looping == 'Y'): number = int(input("\neneter number whose multiplication table you want to print\n")) for i in range(1,11): print(number, "x", i, "=", number*i) else: looping = input("\nDo you want to print another table?\npress Y/y for yes and press any key to exit program.\n") if looping =='y' or looping == 'Y': looping = looping else: sys.exit("program exiting.......")
true
e6e94d3d50a56f104d1ad9993d78f8c44394b753
jdipendra/asssignments
/check square or not.py
1,203
4.25
4
first_side = input("Enter the first side of the quadrilateral:\n") second_side = input("Enter the second side of the quadrilateral:\n") third_side = input("Enter the third side of the quadrilateral:\n") forth_side = input("Enter the forth side of the quadrilateral:\n") if float(first_side) != float(second_side) and float(first_side) != float(third_side) and float(first_side) != float(forth_side): print("The Geometric figure is an irregular shaped Quadrilateral.") elif float(first_side) == float(third_side) and float(second_side) == float(forth_side) and float(first_side) != float(second_side): digonal1 = input("Enter first digonal:\n") digonal2 = input("Enter second digonal:\n") if float(digonal1) == float(digonal2): print("The Geometric figure is a rectangle.") else: print("The Geometric figure is a parallelogram.") elif float(first_side) == float(second_side) == float(third_side) == float(forth_side): digonal1 = input("Enter first digonal:\n") digonal2 = input("Enter second digonal:\n") if float(digonal1) == float(digonal2): print("The Geometric figure is a square.") else: print("The Geometric figure is a rhombus.")
true
24b16e3a48c7688365a31738ad2e12f2f41bc5dc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex03.py
247
4.1875
4
""" .3. Faça um algoritmo utilizando o comando while que mostra uma contagem regres- siva na tela, iniciando em 10 e terminando em 0. Mostrar uma mensagem 'FIM!' após a contagem. """ i = 10 while i >= 0: print(i) i = i - 1 print('FIM')
false
12b0ad3a799b83888c413ba1499b78b3cbe05170
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex08.py
725
4.15625
4
""" Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média destas notas. Uma nota válida deve ser, obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota possua um valor válido, este fato deve ser informado ao usuário e o programa termina. """ nota1 = float(input("Informe a nota1: ")) nota2 = float(input("Informe a nota2: ")) media = (nota1+nota2)/2 if (nota1 >= 0.0) and (nota1 <= 10.0) and (nota2 >= 0.0) and (nota2 <= 10.0): print(f"Nota1 válida = {nota1}") print(f"Nota2 válida = {nota2}") print("Média = {:.2f}".format(media)) else: print("Uma das notas é inválida") print("Tente outra vez com valores válidos de 0.0 a 10.0")
false
677274c5c2e5ef86e3090e5501182c28e1d7acf3
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex21.py
1,216
4.15625
4
""" Escreva o menu de opções abaixo. Leia a opção do usuário e execute a operação escolhida. Escreva uma mensagem de erro se a opção for inválida. Escolha a opção: 1 - Soma de 2 números. 2 - Diferença entre 2 números. (maior pelo menor). 3 - Produto entre 2 números. 4 - Divisão entre 2 números (o denominador não pode ser zero). opção = """ print(" ---- Informe sua escolha abaixo ---- ") print("1 - Soma ") print("2 - Diferença (M-m)") print("3 - Produto ") print("4 - Divisão ") op = int(input("Escolha de opção: ")) if (op > 0) and (op < 5): n1 = int(input("1º Número: ")) n2 = int(input("2º Número: ")) if op == 1: print("{} + {} = {}".format(n1, n2, n1+n2)) elif op == 2: if n1 > n2: print("{} - {} = {}".format(n1, n2, n1 - n2)) else: print("{} - {} = {}".format(n1, n2, n2 - n1)) elif op == 3: print("{} * {} = {}".format(n1, n2, n1 * n2)) else: # numerador = n1 denominador = n2 if denominador == 0: print("O denominador(n2) não pode ser zero") else: print("{} / {} = {:.2f}".format(n1, n2, n1 / n2)) else: print("Opção inválida.")
false
6bdaa9fca5f74779af13721837fc1bf30625af36
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_22_ao_41/S05_Ex28.py
1,237
4.15625
4
""" .28. Faça um programa que leia três números inteiros positivos e efetue o cálculo de uma das seguintes médias de acordo com um valor númerico digitado pelo usuário. - (a) Geométrica : raiz³(x * y * z) - (b) Ponderada : (x + (2 * y) + (3 * z)) / 6 - (c) Harmônica : 1 / (( 1 / x) + (1 / y) + (1 / z)) - (d) Aritmética: (x + y + z)/3 """ x = int(input("Informe o valor de X: ")) y = int(input("Informe o valor de Y: ")) z = int(input("Informe o valor de Z: ")) print("A - Geométrica") print("B - Ponderada") print("C - Harmônica") print("D - Aritmética") op = input("Escolha uma média acima: ") geometrica = (x * y * z) ** (1/3) ponderada = (x + (2 * y) + (3 * z)) / 6 harmonica = 1 / (( 1 / x) + (1 / y) + (1 / z)) aritmetica = (x + y + z)/3 if op == "A" or op == "a": print("A - Geométrica escolhida \n") print("Média = {:.2f}".format(geometrica)) elif op == "B" or op == "b": print("B - Ponderada escolhida \n") print("Média = {:.2f}".format(ponderada)) elif op == "C" or op == "c": print("C - Harmônica escolhida \n") print("Média = {:.2f}".format(harmonica)) elif op == "D" or op == "d": print("D - Aritmética escolhida \n") print("Média = {:.2f}".format(aritmetica))
false
ab98f9c6ff4f60984dba33b33038588020bae6bc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex13.py
645
4.21875
4
""" Faça um algoritmo que calcule a média ponderada das notas de 3 provas. A primeira e a segunda prova tem peso 1 e a terceira tem peso 2. Ao final, mostrar a média do aluno e indicar se o aluno foi aprovado ou reprovado. A nota para aprovação deve ser igual ou superior a 60 pontos. """ nota1 = float(input("nota1: ")) nota2 = float(input("nota2: ")) nota3 = float(input("nota3: ")) divisor = ((nota1 * 1) + (nota2 * 1) + (nota3 * 2)) dividendo = 1 + 1 + 2 media = divisor/dividendo if media >= 6.0: print("Aprovado") print("Media = {:.2f}".format(media)) else: print("Reprovado") print("Media = {:.2f}".format(media))
false
d80274fec662b690fff77f8900d4c6b5c25bb132
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção10-Expressões_Lambdas_e_Funções_Integradas/MinAndMax.py
1,784
4.28125
4
""" Min() e Max() max() -> retorna o maior valor ou o maior de dois ou mais elementos # Exemplos lista = [1, 2, 8, 4, 23, 123] print(max(lista)) tupla = (1, 2, 8, 4, 23, 123) print(max(tupla)) conjunto = {1, 2, 8, 4, 23, 123} print(max(conjunto)) dicionario = {'a': 1, 'b': 2, 'c': 8, 'd': 4, 'e': 23, 'f': 123} print(max(dicionario.values())) # Faça um programa que receba dois valores e retorna o maior valor vlr1 = int(input("VALOR 1: ")) vlr2 = int(input("VALOR 2: ")) print(max(vlr1, vlr2)) print(max(1, 34, 15, 65, 12)) print(max('a', 'abc', 'ab')) print(max('a', 'b','c', 'g')) min() -> Contrário do max() # outros exemplos nomes = ['Arya', 'Joel', 'Dora', 'Tim', 'Ollivander'] print(max(nomes)) print(min(nomes)) print(max(nomes, key=lambda nome: len(nome))) print(min(nomes, key=lambda nome: len(nome))) """ musicas = [ {"titulo": "Thunderstruck", "tocou": 3}, {"titulo": "Dead Skin Mask", "tocou": 2}, {"titulo": "Back in Black", "tocou": 4}, ] print(max(musicas, key=lambda musica: musica['tocou'])) print(min(musicas, key=lambda musica: musica['tocou'])) # DESAFIO! imprimir o titulo da musica mais e menos tocada print('desafio') print(max(musicas, key=lambda musica: musica['tocou'])['titulo']) print(min(musicas, key=lambda musica: musica['tocou'])['titulo']) # DESAFIO! imprimir o titulo da musica mais e menos tocada sem usar o min(), max() e lambda print('desafio 2') max = 0 for musica in musicas: if musica['tocou'] > max: max = musica['tocou'] for musica in musicas: if musica['tocou'] == max: print(musica['titulo']) min = 99999 for musica in musicas: if musica['tocou'] < min: min = musica['tocou'] for musica in musicas: if musica['tocou'] == min: print(musica['titulo'])
false
79b58db5b932f19b7f71f09c37c3942554507803
RjPatil27/Python-Codes
/Sock_Merchant.py
840
4.1875
4
''' John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n = 7 socks with colors arr = [1,2,1,2,3,2,1] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2 . Write code for this problem. ''' from __future__ import print_function def main(): n = int(input().strip()) c = list(map(int, input().strip().split(' '))) pairs = 0 c.sort() c.append('-1') i = 0 while i < n: if c[i] == c[i + 1]: pairs = pairs + 1 i += 2 else: i += 1 print(pairs) if __name__ == '__main__': main()
true
05432b48af09dc9b89fded6fb53181df2645ee53
Mat4wrk/Working-with-Dates-and-Times-in-Python-Datacamp
/1.Dates and Calendars/Putting a list of dates in order.py
569
4.375
4
"""Print the first and last dates in dates_scrambled."" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) """Sort dates_scrambled using Python's built-in sorted() method, and save the results to dates_ordered.""" """Print the first and last dates in dates_ordered.""" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) # Put the dates in order dates_ordered = sorted(dates_scrambled) # Print the first and last ordered dates print(dates_ordered[0]) print(dates_ordered[-1])
true
619f65ba890f6fa2e891f197581b739f02baae40
Jmwas/Pythagorean-Triangle
/Pythagorean Triangle Checker.py
826
4.46875
4
# A program that allows the user to input the sides of any triangle, and then # return whether the triangle is a Pythagorean Triple or not while True: question = input("Do you want to continue? Y/N: ") if question.upper() != 'Y' and question.upper() != 'N': print("Please type Y or N") elif question.upper() == 'Y': a = input("Please enter the opposite value: ") print("you entered " + a) b = input("Please enter the adjacent value: ") print("you entered " + b) c = input("Please enter the hypotenuse value: ") print("you entered " + c) if int(a) ** 2 + int(b) ** 2 == int(c) ** 2: print("The triangle is a pythagorean triangle") else: print("The triangle is not a pythagorean triangle") else: break
true
6273ea18be6a76f5d37c690837830f34f7c516e4
cahill377979485/myPy
/正则表达式/命名组.py
1,351
4.46875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Python 2.7的手册中的解释: (?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1. For example, if the pattern is (?P<id>[a-zA-Z_]\w*), the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'), and also by name in the regular expression itself (using (?P=id)) and replacement text given to .sub() (using \g<id>). """ import re # 将匹配的数字乘以 2 def double(matched): value = int(matched.group('value')) return str(value * 2) def double2(matched): value = int(matched.group(1)) return str(value * 2) s = 'A23G4HFD567' # 用命名group的方式 print(re.sub('(?P<value>\\d+)', double, s)) # ?P<value>的意思就是命名一个名字为value的group,匹配规则符合后面的/d+,具体文档看上面的注释 # 用默认的group带数字的方式 print(re.sub('(\\d+)', double2, s))
true
0c6fcfa855bc02ebc378e1f5d0c1e5bc5014d5b1
HeloiseKatharine/Bioinformatica
/Atividade 1/3.py
821
4.125
4
''' Crie um programa em python que receba do usuário uma sequência de DNA e retorne a quantidade de possíveis substrings de tamanho 4 (sem repetições). Ex.: Entrada: actgactgggggaaa Após a varredura de toda a sequência achamos as substrings actg, ctga, tgac, gact, ctgg, tggg, gggg, ggga, ggaa, gaaa, logo a saída do programa deve ser: Saída: 10 ''' seq = input('Digite a sequência de DNA: ')#recebe a sequência de DNA tam_seq = len(seq) #tamanho da string seq tam_sub = 4 #declarando o tamanho da substring dic_sub = dict() for i in range(tam_seq - tam_sub + 1): #percorre toda a string sub = seq[i:i+tam_sub] #percorre a sequência de acordo com o tamanho da substring if(sub in dic_sub): dic_sub[sub] += 1 else: dic_sub[sub] = 1 quant = len(dic_sub.keys()) print (quant)
false
c3912498bdd7197cd60c10943fefc448909f27f5
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__037.py
628
4.125
4
# conversor de bases numéricas n = int(input('Digite um número inteiro: ')) print('''Escolha umda das bases para a conversão:' [ 1 ] converter para BINÁRIO [ 2 ] converter para OCTAL [ 3 ] converter para HEXADECIMAL''') opção = int(input('Sua opção: ')) if opção == 1: print('{} convertido para BINÁRIO é igual a {}'.format(n, bin(n)[2:])) elif opção == 2: print('{} convertido para OCTAL é igual a {}'.format(n, oct(n)[2:])) elif opção == 3: print('{} convertido para HEXADECIMAL é igual a {}'.format(n, hex(n)[2:])) else: print('Você precisa digitar uma das opções acima!')
false
b27eb11a268eb165af970993edad89d4f4c7694a
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__059.py
1,526
4.15625
4
# criando um menu de opções from time import sleep n1 = float(input('Digite um número qualquer: ')) n2 = float(input('Digite mais um número: ')) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção = int(input('>>>>> Qual é a sua opção? ')) while opção !=5: if opção > 5 or opção == 0: print('Opção inválida. Tente novamente!') if opção == 1: soma = n1+n2 print('A soma de {:.2f} com {:.2f} resulta em {:.2f}.'.format(n1, n2, soma)) elif opção == 2: multi = n1*n2 print('A multiplicação de {:.2f} com {:.2f} resulta em {:.2f}.'.format(n1, n2, multi)) elif opção == 3: if n1 > n2: maior = n1 else: maior = n2 print('O maior número entre {:.2f} e {:.2f} é {:.2f}.'.format(n1, n2, maior)) elif opção == 4: print('Informe os números novamente:') n1 = float(input('Primeiro valor: ')) n2 = float(input('Segundo valor: ')) sleep(1) print('-==-'*8) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção = int(input('>>>>> Qual é a sua opção? ')) if opção == 5: print('Finalizando...') sleep(1) print('-==-'*8) print('Fim do programa. Volte sempre!')
false
5c5199249efa2ba277218ed47e4ae2554a0bbf7e
Adi7290/Python_Projects
/improvise_2numeric_arithmetic.py
660
4.21875
4
#Write a program to enter two integers and then perform all arithmetic operators on them num1 = int(input('Enter the first number please : \t ')) num2 = int(input('Enter the second number please :\t')) print(f'''the addittion of {num1} and {num2} will be :\t {num1+num2}\n the subtraction of {num1} and {num2} will be :\t {num1-num2}\n the multiplication of {num1} and {num2} will be :\t {num1*num2}\n the division of {num1} and {num2} will be :\t {num1/num2}\n the power of {num1} and {num2} will be :\t {num1**num2}\n the modulus of {num1} and {num2} will be :\t {num1%num2}\n the floor division of {num1} and {num2} will be :\t {num1//num2}\n''')
true
4cc7aabb1e5e2b48cc90c607acce1b67f9fac93d
Adi7290/Python_Projects
/Herons formula.py
350
4.28125
4
#Write a program to calculate the area of triangle using herons formula a= float(input("Enter the first side :\t")) b= float(input("Enter the second side :\t")) c= float(input("Enter the third side :\t")) print(f"Side1 ={a}\t,Side2 = {b}\t,Side3={c}") s = (a+b+c)/2 area=(s*(s-a)*(s-b)*(s-c))**0.5 print(f"Semi = {s}, and the area = {area}")
true
ea0b627a1ee97b93acd9087b18e36c3fa5d10b4d
Adi7290/Python_Projects
/singlequantity_grocery.py
942
4.1875
4
'''Write a program to prepare a grocery bill , for that enter the name of items , quantity in which it is purchased and its price per unit the display the bill in the following format *************BILL*************** item name item quantity item price ******************************** total amount to be paid : *********************************''' name = input('Enter the name of item purchased :\t') quantity = int(input('Enter the quantity of the item :\t')) amount = int(input('Enter the amount of the item :\t')) item_price = quantity * amount print('*****************BILL****************') print(f'Item Name\t Item Quantity\t Item Price') print(f'{name}\t\t {quantity}\t\t {item_price}') print('************************************') print(f'Price per unit is \t \t {amount}') print('************************************') print(f'Total amount :\t\t{item_price}') print('************************************')
true
2b786c15f95d48b9e59555d2557cc497d922d948
Adi7290/Python_Projects
/Armstrong_number.py
534
4.40625
4
"""Write a program to find whether the given number is an Armstrong Number or not Hint:An armstrong number of three digit is an integer such that the sum of the cubes of its digits is equal to the number itself.For example 371 is the armstrong number since 3**3+7**3+1**3""" num = int(input('Enter the number to check if its an Armstrong number or not :\t')) orig = num sm =0 while num>0: sm = sm+(num%10)*(num%10)* (num%10) num =num//10 if orig == sm: print('Armstrong') else: print('Not Armstrong')
true
503700558831bf7513fc8987bb669f0e17d144c0
deepika7007/bootcamp_day2
/Day 2 .py
1,301
4.1875
4
#Day 2 string practice # print a value print("30 days 30 hour challenge") print('30 days Bootcamp') #Assigning string to Variable Hours="Thirty" print(Hours) #Indexing using String Days="Thirty days" print(Days[0]) print(Days[3]) #Print particular character from certin text Challenge="I will win" print(challenge[7:10]) #print the length of the character Challenge="I will win" print(len(Challenge)) #convert String into lower character Challenge="I Will win" print(Challenge.lower()) #String concatenation - joining two strings A="30 days" B="30 hours" C = A+B print(C) #Adding space during Concatenation A="30days" B="30hours" C=A+" "+B print(C) #Casefold() - Usage text="Thirty Days and Thirty Hours" x=text.casefold() print(x) #capitalize() usage text="Thirty Days and Thirty Hours" x=text.capitalize() print(x) #find() text="Thirty Days and Thirty Hours" x=text.find() print(x) #isalpha() text="Thirty Days and Thirty Hours" x=text.isalpha() print(x) #isalnum() text="Thirty Days and Thirty Hours" x=text.isalnum() print(x) Result: 30 days 30 hour challenge 30 days Bootcamp Thirty T r win 10 i will win 30 days30 hours 30days 30hours thirty days and thirty hours Thirty days and thirty hours -1 False False ** Process exited - Return Code: 0 ** Press Enter to exit terminal
true
5571025882b22c9211572e657dd38b1a9ecdfa74
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/extra_sum_of_two.py
342
4.1875
4
#Program which will add two numbers together #User has to input two numbers - number1 and number2 number1 = int(input("Number a: ")) number2 = int(input("Number b: ")) #add numbers number1 and number2 together and print it out print(number1 + number2) #TEST DATA #Input 1, 17 -> output 18 #Input 2, 5 -> output 7 #Input 66, 33 -> output 99
true
fa98a79e66cd7e8575c857dabad5877c3b78cd87
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/06_input-validation.py
816
4.25
4
#User has to input a number between 1 and 10 #eg. if user inputs 3, the result will be as follows: 3 -> 3*1=3, 3*2=6, 3*3=9 #ask a user to input a number number = int(input("Input number between 1 and 10: ")) #if the input number is 99 than exit the program if number == 99: exit() # end if #if the number isn't the one we want, the user will have to submit it again while number < 1 or number > 10: print("Number needs to be BETWEEN 1 and 10") number = int(input("Input number between 1 and 10: ")) # end while #times table running in a for loop with a range of 12 for count in range(12): table = (count+1) * number #multiply count by the inputted number print(str(count + 1) + " * " + str(number) + " = " + str(table)) #print out a result # end for # 27.9.19 EDIT - updated variable naming
true
15e022eb2fbc2d17ee9dd7787a5c301d43dbb89a
GitLeeRepo/PythonNotes
/basics/sort_ex1.py
777
4.59375
5
#!/usr/bin/python3 # Examples of using the sorted() function # example function to be used as key by sorted function def sortbylen(x): return len(x) # List to sort, first alphabetically, then by length a = [ 'ccc', 'aaaa', 'd', 'bb'] # Orig list print(a) # Sorted ascending alphabetic print(sorted(a)) # sorted decending alphabetc print(sorted(a, reverse=True)) # use the len() function to sort by length print(sorted(a, key=len)) # use my own custom sort key function print(sorted(a, key=sortbylen)) # use my custom sort key function reversed print(sorted(a, key=sortbylen, reverse=True)) # Orig list still unchanged print(a) # but the sort() method will change the underlying list # unlike the sorted function call which creates a new one a.sort() print(a)
true
8da7f3ba63ae287850cb95fdaf6991da36855947
GitLeeRepo/PythonNotes
/basics/python_sandbox01.py
1,833
4.1875
4
#!/usr/bin/python3 # Just a sandbox app to explore different Python features and techniques for learning purposes import sys def hello(showPrompt=True): s = "Hello World!" print (s) #using slice syntax below print (s[:5]) #Hello print (s[6:-1]) #World print (s[1:8]) #ello wo print (s[1:-4]) #ello wo - same result indexing from right if len(sys.argv) > 1: print ("Command line args: " + str(sys.argv[1:])) #print the command line args if they exists if showPrompt: name = input ("Name?") print ("Hello " + name) print ("Hello", name) #both valid, 2nd adds its own space else: print ("Input not selected (pass True on hello() method call to display input prompt)") def listDemos(): list1 = [1, 2, 3] print(list1) list2 = [4, 5, 6] list3 = list1 + list2 #adds list2 to the end of list1 print(list3) list4 = list2 + list1 #adds list1 to the end of list2 print(list4) print("List pointer:") list1Pointer = list1 #they point to same location list1[0] = "1b" print(list1) print(list1Pointer) print("List copy") list1Copy = list1[:] #makes a copy, two different lists list1[0] = 1 print(list1) print(list1Copy) def menuChoices(): print ("Choose:") print ("1 - call hello (demo strings and argv command lines)") print ("2 - list demo") print ("d - display menu choices") print ("x - exit program") def main(): menuChoices() select = input("Selection: ") while select != "x": if select == "1": hello(False) #hello() without arg will use the default specified in parameter def elif select == "2": listDemos() elif select == "d": menuChoices() select = input("Selection: ") main()
true
66d407d714258a6aceea8e800a10ba5994af040a
ecastillob/project-euler
/101 - 150/112.py
1,846
4.40625
4
#!/usr/bin/env python # coding: utf-8 """ Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ # In[1]: def arriba(N): valor = -1 actual = -1 for n_str in str(N): actual = int(n_str) if actual < valor: return False valor = actual return True # In[2]: def abajo(N): valor = 10 actual = 10 for n_str in str(N): actual = int(n_str) if actual > valor: return False valor = actual return True # In[3]: def es_bouncy(N): return not (arriba(N) or abajo(N)) # In[4]: arriba(134468), abajo(66420), es_bouncy(155349) # In[5]: def contar_bouncies(RATIO_LIMITE): contador = 0 ratio = 0 i = 100 while (ratio != RATIO_LIMITE): if es_bouncy(i): contador += 1 ratio = contador / i i += 1 return [contador, i - 1, ratio] # In[6]: contar_bouncies(0.5) # [269, 538, 0.5] # In[7]: contar_bouncies(0.9) # [19602, 21780, 0.9] # In[8]: contar_bouncies(0.99) # [1571130, 1587000, 0.99]
true
6a442bcbc6464c0e325b859b78633111ae48a649
al0fayz/python-playgrounds
/fundamental/1-variabel.py
1,045
4.3125
4
#example variabel in python x = 5 y = 2 kalimat = "hello world" kalimat1 = 'hai all!' print(x) print(y) print(kalimat) print(kalimat1) a , b , c = 1, 2, 3 text1, text2, text3 = "apa", "kabar", "indonesia?" print(a, b, c) print(text1, text2, text3) result1 = result2 = result3 = 80 print(result1, result2, result3) print("your weight is" , result1) #integer print("i like " + text3) #string #example global variabel # this is a global variabel name = "alfa" def test(): # i can call variabel global inside function print("my name is " + name) #call function test() # global variabel can call inside or outside function # example local varibel def coba(): address = "jakarta" #this is local variabel you can call on outside func print(address) # if you want set global varibel inside function you can add global #ex : global bahasa #you must defined first , you can't insert value directly bahasa = "indonesia" print(bahasa) coba() # i try call variabel global print("my language is "+ bahasa)
false
cfcbe016443d6a8fa6bd958d56d8e49705269b81
al0fayz/python-playgrounds
/fundamental/6-tuples.py
726
4.3125
4
#contoh tuples """ tuples bersifat ordered, tidak bisa berubah, dan dapat duplicate """ contoh = ("satu", "dua", "tiga", "tiga") print(contoh) #acces tuples print(contoh[0]) print(contoh[-1]) print(contoh[1:4]) #loop tuples for x in contoh: print(x) #check if exist if "satu" in contoh: print("yes exist") #length of tuples print(len(contoh)) #kita tidak bisa menghapus element atau menambahkan element pada tuples # tapi kita bisa delete tuples del contoh #delete tuples #join tuples tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) #tuples constructor untuk membuat tuples thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets print(thistuple)
false
7643854c54690814e2744e3cd80bc02ec02770e1
aaryanredkar/prog4everybody
/L1C2_Fibonacci.py
229
4.28125
4
Value = int(input("Please enter MaxValue for Fibonacci sequence : ")) print ("The fibonacci sequence <=",Value, "is: ") a, b = 0, 1 temp = 0 print ("0 ") while (b <= Value): print (b) temp = a+b a = b b = temp
false
3ef7c91a7f379e5b8f4f328c0e79a9238d6bce08
aaryanredkar/prog4everybody
/project 2.py
327
4.3125
4
first_name = input("Please enter your first name: ") last_name = input("Please enter your last name: ") full_name = first_name +" " +last_name print("Your first name is:" + first_name) print("Your last name is:" + last_name) print ("Your complete name is ", full_name) print("Your name is",len(full_name) ,"characters long")
true
dd6b6c00d59cb5a26089744badf9ac3e3588e7c7
davronismoilov/pdp-1-modul
/task 6_2.py
489
4.1875
4
"""Standart kiruvchi ma'lumotdagi vergul bilan ajratilgan so'zlar ketma-ketligini teskari tartibda chiqaradigan dastur tuzing Masalan: Ismlar: john, alice, bob Natija: bob, alice, john""" words = input("Vergul bilan ajratib so'zlar kiriting:\n Ismlar: ").split(sep=",") #First metod slise orqali chiqarish teskarisiga print('Natija :',*words[::-1]) words.reverse() print('Natija :',end=" ") for i in range (len(words)): print(words[i],end=",")
false
b8ab12a52930764e694596ad1c4ec4346fb82590
pankajmore/AI_assignments
/grid.py
1,243
4.15625
4
#!/usr/bin/python class gridclass(object): """Grid class with a width, height""" def __init__(self, width, height,value=0): self.width = width self.height = height self.value=value def new_grid(self): """Create an empty grid""" self.grid = [] row_grid = [] for col in range(self.width): for row in range(self.height): row_grid.append(self.value) self.grid.append(row_grid) row_grid = [] # reset row return self.grid def print_grid(self): for row in range(self.height): for col in range(self.width): print(self.grid[row][col],end=" ") print() def insertrow(self,pos): cell_value = '_' self.height+=1 self.grid.insert(pos,[cell_value]*self.width) def insertcolumn(self,pos): cell_value='_' for i in range(self.height): self.grid[i].insert(pos,cell_value) self.width+=1 def edit(self,x,y,val): self.grid[x][y]=val #my_grid = grid(10, 10) #print ("Empty grid ...") #my_grid.new_grid() #my_grid.print_grid() #my_grid.insertrow(3) #my_grid.insertcolumn(8) #my_grid.print_grid()
false
6cd1676e716a609f138136b027cbe6655c7292a4
obrienadam/APS106
/week5/palindrome.py
1,178
4.21875
4
def is_palindrome(word): return word[::-1] == word if __name__ == '__main__': word = input('Enter a word: ') if is_palindrome(word): print('The word "{}" is a palindrome!'.format(word)) else: print('The word "{}" is not a palindrome.'.format(word)) phrase = input('What would you like to say?: ').lower() if phrase == 'hello': print('Hello to you too!') elif phrase == 'goodbye': print('Goodbye!') elif phrase == 'how are you doing today?': print('Fine, thank you!') else: print('I did not understand that phrase.') from random import randint num = randint(1, 10) guess = int(input('Guess a number between 1 and 10: ')) if 1 <= guess <= 10: if guess == num: print('Good guess!') else: print('Terrible guess. The number was {}'.format(num)) else: print(num, 'is not between 1 and 10...') from random import randint num = randint(1, 10) guess = int(input('Guess a number between 1 and 10: ')) if not 1 <= guess <= 10: print(num, 'is not between 1 and 10...') else: if guess == num: print('Good guess!') else: print('Terrible guess. The number was {}'.format(num))
true
ab1df5f6495bf2de81da4b47c6f82acf8b9645ae
aaskorohodov/Learning_Python
/Обучение/Set (множество).py
477
4.15625
4
a = set() print(a) a = set([1,2,3,4,5,"Hello"]) print(a) b = {1,2,3,4,5,6,6} print(b) a = set() a.add(1) print(a) a.add(2) a.add(10) a.add("Hello") print(a) a.add(2) print(a) a.add("hello") print(a) for eo in a: print(eo) my_list = [1,2,1,1,5,'hello'] my_set = set() for el in my_list: my_set.add(el) print(my_set) my_set = set(my_list) print(my_set) my_list = list(my_set) print(my_list) a = {"hello", "hey", 1,2,3} print(5 in a) print(15 not in a)
false
e0dd4c5a6ead7cd585d9d4cf387e6d4c8849accb
riterdba/magicbox
/cl11.py
283
4.125
4
#!/usr/bin/python3 class Square(): def __init__(self, a): self.a = a def __repr__(self): return ('''{} на {} на {} на {}'''.format(self.a, self.a, self.a, self.a)) sq1 = Square(10) sq2 = Square(23) sq3 = Square(77) print(sq1) print(sq2) print(sq3)
false